TextView inside Fragment in ViewPager is null on orientation change - java

I have a MainActivity inside I create ViewPager withFragments. I am using savedInstanceState to store values to set TextView after orientation changed. I also want to change value e.g. using button in MainActivity. Button works properly, but if I change the orientation then Button cannot set TextView in Fragment because TextView is now null.
MyFragment
public class MyFragment extends Fragment {
private TextView textView;
private String info;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.item_weather, container, false);
textView = view.findViewById(R.id.text_view);
Bundle bundle = getArguments();
info = bundle.getString("info");
setInfo(info);
return view;
}
public void setInfo(String info) {
this.info = info;
textView.setText(info); //here is the error
}
}
In MainActivity.java in OnCreate
myFragment = new MyFragment();
viewPager = findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(10);
List<Fragment> fragments = new ArrayList<>();
fragments.add(myFragment);
pagerAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(pagerAdapter);
MyPagerAdapter looks like this:
public class MyPageAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
}
As I said everything works, but after orientation chage if I use Button I got an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Any ideas how to solve this?
edit:
full error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app.myapp, PID: 15400
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.app.myapp.fragments.myFragment.setInfo(myFragment.java:53)
at com.example.app.myapp.MainActivity.onOptionsItemSelected(MainActivity.java:195)
at android.app.Activity.onMenuItemSelected(Activity.java:3543)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:407)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
at android.widget.AbsListView$3.run(AbsListView.java:4052)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Into the fragment try to initialize the textView in the on the onViewCreated method:
#Override
public View onViewCreated(view: View, savedInstanceState: Bundle) {
// Your initialization code here
}

Solution:
Ok, EpicPandaForce thanks for hints.
To solve this i used in MainActivity
#Override
protected void onResume() {
super.onResume();
viewPager.setAdapter(pagerAdapter);
}
#Override
protected void onPause() {
super.onPause();
viewPager.setAdapter(null);
}

Related

Android app crashes when activity is initialised from fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am currently trying to create a calendar app in android studio. The app contains a calendar with different "Views" e.g. monthly view, weekly view, and daily view.
The app uses fragments as pages and each view is an activity.
This is the code for the fragment and buttons to initialise each view
public class CalendarFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
Button btn1 = (Button) v.findViewById(R.id.openCalendar);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(),CalendarActivity.class);
startActivity(intent);
}
});
Button btn2 = (Button) v.findViewById(R.id.openWeek);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), WeekViewActivity.class);
startActivity(intent);
}
});
return v;
}
The first button which displays the monthly view of the calendar called "CalendarActivity" in code works fine but when the second button is clicked which displays the weekly view of the calendar, causes the app to crash and gives the following error in the logcat
2022-05-13 14:44:59.642 15183-15183/com.example.finalyearproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalyearproject, PID: 15183
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finalyearproject/com.example.finalyearproject.WeekViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3685)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at com.example.finalyearproject.CalendarUtils.monthYearFromDate(CalendarUtils.java:16)
at com.example.finalyearproject.WeekViewActivity.setWeekView(WeekViewActivity.java:40)
at com.example.finalyearproject.WeekViewActivity.onCreate(WeekViewActivity.java:29)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Activity.performCreate(Activity.java:8034)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1341)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7842) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
I am not sure what the problem is as I have been following a tutorial and the other features work. I have also included the code for each activity below.
Monthly View
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setMonthView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void nextMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusMonths(1);
setMonthView();
}
public void previousMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusMonths(1);
setMonthView();
}
Weekly View
public class WeekViewActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_view);
initWidgets();
setWeekView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setWeekView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> days = daysInWeekArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(days, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void previousWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusWeeks(1);
setWeekView();
}
public void nextWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusWeeks(1);
setWeekView();
}
Any suggestions would be greatly appreciated.
My suggestions:
Firstly you didn't initialized CalendarUtils.selectedDate
Cover code with breakpoints for. debugging or with Log.d() messages to find, which variable is null

Unable to send Strings from one Fragment to another via Bundles

I am trying to send two strings via a bundle to the next fragment but the app crashes even before I get to the first fragment.
I get this error in the second fragment:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.guessit, PID: 22360
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.example.android.guessit.GameFlow.FragmentAnswer1.onCreateView(FragmentAnswer1.java:125)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1696)
at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:299)
at androidx.fragment.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:259)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
at androidx.viewpager.widget.ViewPager.setCurrentItemInternal(ViewPager.java:669)
at androidx.viewpager.widget.ViewPager.setCurrentItemInternal(ViewPager.java:631)
at androidx.viewpager.widget.ViewPager.setCurrentItem(ViewPager.java:612)
at com.example.android.guessit.GameFlow.GameActivity.setViewPager(GameActivity.java:152)
at com.example.android.guessit.GameFlow.FragmentOneCategory$6.onClick(FragmentOneCategory.java:190)
at android.view.View.performClick(View.java:7352)
at android.view.View.performClickInternal(View.java:7318)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27800)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
I know that this means that the string value that I am trying to receive in the second fragment means that there is no value for that string but I don't know where the problem here is because the strings I am trying to send are not null.
This is the code I am using for the bundle in the first fragment (using this in onCreatView):
FragmentAnswer1 frag1 = new FragmentAnswer1();
Bundle args = new Bundle();
args.putString("question_1", question);
args.putString("answer_1", answer);
frag1.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.container, frag1).commit(); // there is a message that says that "beginTransaction" may produce a nullPointer
Here is the code to receive the strings in the second fragment (currently also in onCreateView)
question = getArguments().getString("question_1"); // error is in this line
answer = getArguments().getString("answer_1");
question1.setText(question);
rightAnswer.setText(answer);
I already tried to move the above code into the onStartmethod but I still get the same error. I also tried using this solution but its not working for me. I did not find any other solution or method on how to resolve the problem.
Please let me know if you need more informations. Any help is much appreciated!
I have now found the correct way to send data from one Fragment to another while having a ViewPager. We have to use a ViewModel.
First we have to create a ViewModel, in this case our goal is to send a String from Fragment 1 to Fragment 2. Here is the code for the ViewModel with Getter and Setter method for the String:
public class ViewModelString extends ViewModel {
private MutableLiveData<String> mString = new MutableLiveData<>();
public MutableLiveData<String> getmString() {
return mString;
}
public void setmString(MutableLiveData<String> mString) {
this.mString = mString;
}
}
Then in Fragment 1 from where we want to sent the string we need to first initialize the ViewModel in onCreate.
public class Fragment1 extends Fragment {
private ViewModelString viewModel;
public Fragment1() {
// Required empty public constructor
}
public static Fragment1 newInstance() {
return new Fragment1();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize ViewModel here
viewModel = ViewModelProviders.of(requireActivity()).get(ViewModelString.class);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
String hello = "hello";
viewModel.setmString(hello);
}
}
Then in the second Fragment we also have to first initialize the viewModel and then create an observer. Here we then take the String that is stored in the ViewModel and set a TextView to its value:
public class Fragment2 extends Fragment {
private ViewModelString viewModel;
public Fragment2() {
// Required empty public constructor
}
public static Fragment2 newInstance() {
return new Fragment2();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize ViewModel here
viewModel = ViewModelProviders.of(requireActivity()).get(ViewModelString.class);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
TextView textView = findViewById(R.id.yourTextViewId);
// Gets the string
viewModel.getmString().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
}
...
}
I hope this helps anyone! Please feel free to edit my post.
Use Bundle to send String:
//Put the value
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
YourFragmentName ldf = new YourFragmentName ();
ldf.setArguments(args);
//Inflate the fragment
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
In onCreateView of the new Fragment:
//Retrieve the value
Bundle bundle = this.getArguments();
if (bundle != null) {
String value = bundle.getString("YourKey");
}
Use a Bundle. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("Key", "value");
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, frag1).commit()
Bundle has put methods for lots of data types. See this
Then in your Fragment, retrieve the data in onCreate() method like:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getString(Key);
}
try this.
var fragment: MainFragment =MainFragment()
val args = Bundle()
args.putString("question_1", "My question")
args.putString("answer_1", "My answer")
fragment.setArguments(args)
fragmentManager.beginTransaction().add(R.id.fragment_content, fragment).commit()

NullPointerException on views outside of OnActivityCreated/OnCreateView

When any sort of view is called outside of the OnCreateView method (or OnActivtivityCreated method for that matter, I have tried both), I get a NullPointerException. To communicate between fragments, I used the interface method which, through my research, seems to be the best way to do it. Unfortunately, I suspect that my error comes from the way that the MainActivity finds the Fragments.
To try to debug what I have so far, I used System.out.println() on the object in OnCreateView()/OnActivityCreated() and there is a memory address meaning it exists and is NOT null, yet when I call it outside of the function from MainActivity, it becomes null...?
Can someone shed some light into my situation? Thanks! (BTW, I have taken some useless parts of the code out)
Tab2Home.java
#Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
spinner = (Spinner)getActivity().findViewById(R.id.tipSpinner);
adapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(), R.array.tipArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
serviceRate=(RatingBar) getActivity().findViewById(R.id.serviceBar);
//THE OBJECT BELOW IS WHERE THE NULLPOINTEREXCEPTION IS COMING FROM
billAmount = (EditText)getActivity().findViewById(R.id.billEditText);
System.out.println(billAmount); //Surprisingly, this is not null IN the method.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
}
public void transferInfo(){
double bill;
if (String.valueOf(billAmount.getText()).isEmpty()) //billAmount is null OUTSIDE of the method.
bill = 0.00;
else
bill = Double.parseDouble(String.valueOf(billAmount.getText()));
odsl.setData( //odsl is the OnDataSetListener object.
bill,
Integer.parseInt(String.valueOf(spinner.getItemAtPosition(3))),
Integer.parseInt(String.valueOf(numPeopleEdit.getText()))
);
}
public interface OnDataSetListener {
public void setData(double bill, int tip, int ppl);
}
#Override
public void onAttach(Context context){
super.onAttach(context);
try {
odsl = (OnDataSetListener) context;
} catch (Exception e){}
}
And the MainActivity.java
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 2){
Tab2Home homefrag = (Tab2Home) mSectionsPagerAdapter.getItem(1);
homefrag.transferInfo();
System.out.println(".transferInfo() has been called");
}
}
#Override
public void onPageSelected(int position) {
if (position == 3){
Tab2Home homefrag = (Tab2Home) mSectionsPagerAdapter.getItem(2);
homefrag.transferInfo();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void setData(double bill, int tip, int ppl) {
Tab3Summary summaryfrag = (Tab3Summary) mSectionsPagerAdapter.getItem(2);
summaryfrag.updateInfo(bill, tip, ppl);
}
EDIT:
Here is the error message:
05-23 02:28:00.352 31339-31339/com.uottawa.bond.simpletip E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.uottawa.bond.simpletip, PID: 31339
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.uottawa.bond.simpletip.Tab2Home.transferInfo(Tab2Home.java:97)
at com.uottawa.bond.simpletip.MainActivity$1.onPageScrolled(MainActivity.java:64)
at android.support.v4.view.ViewPager.dispatchOnPageScrolled(ViewPager.java:1954)
at android.support.v4.view.ViewPager.onPageScrolled(ViewPager.java:1928)
at android.support.v4.view.ViewPager.pageScrolled(ViewPager.java:1866)
at android.support.v4.view.ViewPager.computeScroll(ViewPager.java:1826)
at android.view.View.updateDisplayListIfDirty(View.java:16037)
at android.view.View.draw(View.java:16834)
at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
at android.support.design.widget.CoordinatorLayout.drawChild(CoordinatorLayout.java:1195)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
at android.view.View.draw(View.java:17071)
at android.view.View.updateDisplayListIfDirty(View.java:16050)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:656)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:662)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:770)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2796)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2604)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2211)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:619)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Find the solution:
1.override the below method
2.Instead of getActivity().findviewbYId use rootView
#Override
public void onViewCreated(View rootView, Bundle savedInstanceState) {
spinner = (Spinner)rootView.findViewById(R.id.tipSpinner);
adapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(), R.array.tipArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
serviceRate=(RatingBar) rootView.findViewById(R.id.serviceBar);
billAmount = (EditText)rootView.findViewById(R.id.billEditText);
System.out.println(billAmount);
}

NullPointerException using fragment transactions [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm starting with android and just getting crazy with the implements of multiple fragments.
I have two fragments in my MainActivity: QuestionDetail and QuestionListFragment.
When I use a fragment transactions to replace the QuestionDetail fragment when someone click in one of the QuestionListFragment options I get a NullPointerException error.
I have been trying to fix this issue for hours. Any help is greatly appreciated.
QuestionDetail
public class QuestionListFragment extends Fragment{
private RecyclerView recView;
public static QuestionAdapter adapter;
private QuestionListener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_question_list, container, false);
recView = (RecyclerView) v.findViewById(R.id.recView);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recView.setLayoutManager(layoutManager);
adapter = new QuestionAdapter(QuestionCatalog.getQuestionCatalog().getQuestionList().getList());
adapter.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (listener!=null) {
listener.onQuestionListener(adapter.getItem(recView.getChildAdapterPosition(v)));
}
}
});
recView.setAdapter(adapter);
}
public interface QuestionListener {
void onQuestionListener(Question q);
}
public void setQuestionListener(QuestionListener listener) {
this.listener=listener;
}
QuestionDetail
public class QuestionDetail extends Fragment {
// We use an ID to know which Question we're using
private long questionId;
public QuestionDetail() {
// 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_question_detail, container, false);
}
#Override
public void onStart() {
super.onStart();
//Fragments don’t include findViewById(). To get a reference to a view, we use getView()
View view = getView();
if (view != null) {
TextView title = (TextView) view.findViewById(R.id.textQuestion);
Question question = QuestionCatalog.getQuestionCatalog().getQuestionList().getList().get((int) questionId);
title.setText(question.getName());
TextView kind = (TextView) view.findViewById(R.id.textKind);
kind.setText(question.getKind());
}
}
public void showDetails(String texto) {
TextView txtName = (TextView)getView().findViewById(R.id.textQuestion);
TextView txtKind = (TextView)getView().findViewById(R.id.textKind);
txtName.setText(texto);
txtKind.setText(texto);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements QuestionListFragment.QuestionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuestionListFragment frg =(QuestionListFragment)getFragmentManager().findFragmentById(R.id.listFragment);
frg.setQuestionListener(this);
}
#Override
public void onQuestionListener(Question q) {
Toast.makeText(this, "num: " + q.getName(),
Toast.LENGTH_LONG).show();
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
QuestionDetail f1 = new QuestionDetail();
f1.showDetails(q.getName());
t.replace(R.id.detailFragment,f1);
t.addToBackStack(null);
t.commit();
}
stacktrace
08-04 09:54:11.914 22277-22277/com.hfad.predictandwin E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.hfad.predictandwin.Fragments.QuestionDetail.showDetails(QuestionDetail.java:50)
at com.hfad.predictandwin.MainActivity.onQuestionListener(MainActivity.java:34)
at com.hfad.predictandwin.Fragments.QuestionListFragment$1.onClick(QuestionListFragment.java:55)
at com.hfad.predictandwin.QuestionAdapter.onClick(QuestionAdapter.java:61)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18786)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
First, don't use getView() in onStart() - You shouldn't have a view to get at that point. Second, you shouldn't be calling methods directly on the Fragment instances from elsewhere, in your case f1.showDetails(q.getName());. There, again, the Fragment has no View. Please see Best practice for instantiating a new Android Fragment for how to pass arguments into Fragment before you load it into the FragmentManager.
Next point - you should initialize your views using findViewById inside of onCreateView just like you did for the other Fragment class. For example,
private TextView txtName, txtKind;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_question_detail, container, false);
txtName = (TextView) rootView.findViewById(R.id.textQuestion);
txtKind = (TextView) rootView.findViewById(R.id.textKind);
// TODO: Read the link how to use these
Bundle arguments = getArguments();
Question question = QuestionCatalog.getQuestionCatalog()
.getQuestionList().getList().get((int) questionId);
showQuestion(question);
return view;
}
private void showQuestion(Question q) {
txtName.setText(q.getName());
txtKind.setText(q.getKind());
}
in QuestionListFragment:
We set click listener for recView, not adapter. You should replace adapter.setOnClickListener with
recView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recView, new ClickListener() {
#Override
public void onClick(View view, int position) {
// do something with position.
}
#Override
public void onLongClick(View view, int position) {
}
}));
in QuestionDetail:
questionId wasn't initialized but you have use it in this line:
Question question = QuestionCatalog.getQuestionCatalog().getQuestionList().getList().get((int) questionId);
Based on stacktrace and your code (not sure which one is line #50 in your QuestionDetail) ether txtName or txtKind evaluates to null (maybe both), so for whatever reason getView().findViewById(R.id.textQuestion) returns null. Probably because getView() in that call doesn't get you a parent view of the TextView in question

NullPointerException when showing a ViewPager a second time

I am using a ViewPager fragment which has two fragments as children. This works great, however when I replace the ViewPager fragment by another fragment and replace this fragment by the ViewPager fragment my application crashes with the following NullPointerException:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:667)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:211)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1319)
at android.view.View.dispatchRestoreInstanceState(View.java:13756)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2888)
at android.view.View.restoreHierarchyState(View.java:13734)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:468)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1094)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
My ViewPager fragment consists of the following source code instanciating the two child fragments in case they are null. Furthermore, the ViewPagerAdapter implementation is instanciated and assigned to the ViewPager.
public class ConnectionPasswordViewPagerFragment extends Fragment
{
private ViewPager vpConnectionPassword;
private ConnectionPasswordViewPagerAdapter paConnectionPassword;
private ConnectionPasswordGeneratorMACAddress passwordGeneratorMACAddress;
private ConnectionPasswordGeneratorSerialNumber passwordGeneratorSerialNumber;
public ConnectionPasswordViewPagerFragment()
{
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if ((this.passwordGeneratorSerialNumber == null) && (this.passwordGeneratorMACAddress == null))
{
this.passwordGeneratorMACAddress = new ConnectionPasswordGeneratorMACAddress();
this.passwordGeneratorSerialNumber = new ConnectionPasswordGeneratorSerialNumber();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_connection_password_view_pager, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
/*if (this.paConnectionPassword == null)
{*/
this.paConnectionPassword = new ConnectionPasswordViewPagerAdapter(this.getChildFragmentManager(), this.getActivity(), this.passwordGeneratorMACAddress, this.passwordGeneratorSerialNumber);
//}
this.vpConnectionPassword = (ViewPager) this.getActivity().findViewById(R.id.vpConnectionPassword);
this.vpConnectionPassword.setAdapter(this.paConnectionPassword);
}
}
The ViewPagerAdapter shown below implementation keeps the reference to the child fragments in an ArrayList and implements the metods getItem(), getCount() as well as getPageTitle(). The class ViewPagerFragment simply extends the support Fragment class and provides the abstract method getPageTitleStringID() implemented by the child fragments.
public class ConnectionPasswordViewPagerAdapter extends FragmentStatePagerAdapter
{
private static final byte NUMBER_OF_FRAGMENTS = (byte) 2;
private ArrayList<ViewPagerFragment> childFragments;
private Activity displayActivity;
public ConnectionPasswordViewPagerAdapter(FragmentManager fragmentMgm, Activity displayAct, ConnectionPasswordGeneratorMACAddress generatorMACAddress, ConnectionPasswordGeneratorSerialNumber generatorSerialNumber)
{
super(fragmentMgm);
this.childFragments = new ArrayList<>(ConnectionPasswordViewPagerAdapter.NUMBER_OF_FRAGMENTS);
this.setDisplayActivity(displayAct);
if (generatorMACAddress != null)
{
this.childFragments.add(generatorMACAddress);
}
if (generatorSerialNumber != null)
{
this.childFragments.add(generatorSerialNumber);
}
}
public Activity getDisplayActivity()
{
return this.displayActivity;
}
public void setDisplayActivity(Activity value)
{
this.displayActivity = value;
}
#Override
public Fragment getItem(int position)
{
return this.childFragments.get(position);
}
#Override
public int getCount()
{
return ConnectionPasswordViewPagerAdapter.NUMBER_OF_FRAGMENTS;
}
#Override
public CharSequence getPageTitle(int position)
{
return this.getDisplayActivity().getString(this.childFragments.get(position).getPageTitleStringID());
}
}
Thanks for your help!
I fixed the issue by simply creating the fragment containing the view pager every time I call the support fragment manager's replace method.
public void onSwitchToConnectionPasswordGenerator(View clickedView)
{
this.fragConnectionPassword = new ConnectionPasswordViewPagerFragment();
this.getSupportFragmentManager().beginTransaction().replace(R.id.flFragmentContainer, this.fragConnectionPassword).commitAllowingStateLoss();
}
I think your Viewpager is in Fragment, and this fragment have setRetainInstance set to true (i have this error too when i try to retain the parent fragment)
Better way is to you can check for FragmentManager to get Fragment if its there, if not then create a new instance as follows:
FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentByTag("YourFragmentName");
if(fragment == null)
fragment = new YourFragment();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(Your_Fragmnet_Container_Layout_id, fragment, fragment.getClass().getSimpleName());
fragmentTransaction.commit;

Categories