0

I'm doing an app with diffrent layout on phones and tablets. For phones I have ViewPager with Fragments and on tablets I have fragments in .xml layout file. I'm getting Null Pointer Exception when I try get particular fragment and use method from activity in that fragment.
How can I fix it? I get Null Pointer when I run app on phone with ViewPager but when I have tablet with fragments in .xml layout it is okay.

Methods in MainActivity:

  private ViewPager viewPager;
    private PagerAdapter adapter;
    private TabLayout tableLayout;

    private void setViewPager(){
            viewPager = findViewById(R.id.viewpager);
            adapter = new PagerAdapter(getSupportFragmentManager(), 2);
            adapter.addFragment(new SunFragment(), "Sun");
            adapter.addFragment(new MoonFragment(), "Moon");

            tableLayout = findViewById(R.id.tabLayout);

            if(viewPager != null) {
                viewPager.setAdapter(adapter);
            }
            if(tableLayout != null){
                tableLayout.setupWithViewPager(viewPager);
            }


        }

        private void refreshView(){
            if(viewPager != null) {
                adapter.getSunFragment().calculateWeather();
                adapter.getMoonFragment().calculateWeather();
            }else if(sunFragment != null){
                sunFragment.calculateWeather();
                moonFragment.calculateWeather();
            }

        }

Part in fragment with Null Pointer when I try use method from activity and get a double value:

 public void calculateWeather(){
        longitude = ((MainActivity)getActivity()).getLon();
        latitude = ((MainActivity)getActivity()).getLat();

    }

View Pager Adapter:

public class PagerAdapter extends FragmentStatePagerAdapter {

    private int fragmentNumber;
    private List<Fragment> fragmentList = new ArrayList<>();
    private List<String> fragmentsNameList = new ArrayList<>();


    public PagerAdapter(FragmentManager fm, int fragmentNumber){
        super(fm);
        this.fragmentNumber = fragmentNumber;
    }

    public void addFragment(Fragment fragment, String name){
        fragmentList.add(fragment);
        fragmentsNameList.add(name);
    }

    public SunFragment getSunFragment(){
        return (SunFragment)fragmentList.get(0);
    }

    public MoonFragment getMoonFragment(){
        return (MoonFragment)fragmentList.get(1);
    }
    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentNumber;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentsNameList.get(position);
    }
}

//Edit

E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.mariusz.astroweather, PID: 4970
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mariusz.astroweather/com.example.mariusz.astroweather.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double com.example.mariusz.astroweather.MainActivity.getLon()' on a null object reference
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:148)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double com.example.mariusz.astroweather.MainActivity.getLon()' on a null object reference
                                                     at com.example.mariusz.astroweather.SunFragment.calculateWeather(SunFragment.java:56)
                                                     at com.example.mariusz.astroweather.MainActivity.refreshView(MainActivity.java:124)
                                                     at com.example.mariusz.astroweather.MainActivity.onCreate(MainActivity.java:49)
                                                     at android.app.Activity.performCreate(Activity.java:6237)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                     at android.os.Looper.loop(Looper.java:148) 
                                                     at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 


com.example.mariusz.astroweather.SunFragment.calculateWeather(SunFragment.java:56) 

is line :

longitude = ((MainActivity)getActivity()).getLon();

add onCreate of MainActivity:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setViewPager();
        refreshView();
    }
  • share the logcat of exception please – Rizwan Atta Mar 04 '18 at 13:32
  • I just forgot, its added now. – Zapp Scierwx Mar 04 '18 at 13:40
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – ADM Mar 04 '18 at 13:45
  • and you are trying to call this " ((MainActivity)getActivity()).getLon();" where in the fragment? – Rizwan Atta Mar 04 '18 at 13:45
  • `getActivity()` returning null . FInd out why . You probably using it outside the Fragment attach lifecycle . – ADM Mar 04 '18 at 13:48
  • I'm calling onAttach in my fragment so I think its not outside: @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof Activity){ a=(Activity) context; mainActivity = (MainActivity)a; } } – Zapp Scierwx Mar 04 '18 at 14:16

1 Answers1

0

As per your comments if. you the fragment's powers to be used inside of the activity then you are bound to do something like this

YourFragment fragment = (YourFragment) getFragmentManager().findFragmentById(R.id.YourFragment);
//any mothed of your fragment that you like
fragment.calculateWeather(); 

FOR CALLING An Activity's method inside of your fragment this is the way to go

Because of your logCat I am foreseeing it that you are using your fragment to activity call method in wrong place maybe! you should use this method of yours in the fragment's OnActivityCreated() instead of using it else where?

// use this 
    public void calculateWeather(){
        longitude = ((MainActivity)getActivity()).getLon();
        latitude = ((MainActivity)getActivity()).getLat();

    }
   //as

  //in your fragment

   @Override

   public void OnActvityCreated(){
   // .... super()....
     //......
     calculateWeather();
     //......
  }
Rizwan Atta
  • 3,222
  • 2
  • 19
  • 31
  • What I want is to getFragment from ViewPager and then use this fragments' method in MainActivity. But looks like getActivity is null in my fragment and I try to figure out why. I'm calling fragment method in MainActivity when user clicks button or sth. – Zapp Scierwx Mar 04 '18 at 14:05
  • I works when I have fragments in xml files, but here I have these fragments in List in PagerAdapter class and cannot actually use findFragmentById. – Zapp Scierwx Mar 04 '18 at 14:19
  • you are using this method of yours where? in your fragments or your activity? just elaborate that and I will try to provide a solution! – Rizwan Atta Mar 04 '18 at 14:21
  • In MainActivity i have PagerAdapter which has List of Fragments and in MainAcitivity I want use calculateWeather() on one of fragment from this list. And I try to do it by this: adapter.getSunFragment().calculateWeather(); – Zapp Scierwx Mar 04 '18 at 14:23
  • everything else seems fine! can you show that where you are calling that refreshView and setViewPager methods by sampling your question with onCreate() of your Activity – Rizwan Atta Mar 04 '18 at 14:28
  • Added to main post. I call them from onCreate actually – Zapp Scierwx Mar 04 '18 at 14:37
  • there are two kinds of fragments to be used can you check that which fragment you are importing in your adapter! it should be v4 support fragment not the app.fragment.. please confirm – Rizwan Atta Mar 04 '18 at 14:51
  • It is android.support.v4.app.Fragment – Zapp Scierwx Mar 04 '18 at 14:53
  • put a safety check in your refresh view and see that either your adapter has any items in it or not! because it seems like that your adapter is not working or doing something wrong ! remove the if null check from your Refresh View while reading your adapter ! if(viewPager != null) {} and also check either your list of fragments is getting filled properly by its getCount! you made – Rizwan Atta Mar 04 '18 at 15:15
  • ViewPagerAdapter works fine, I checked it before I tried to call calculateWeather() from MainActivity. I have to have this null check in refreshView because I dont have it in my xlarge layout. – Zapp Scierwx Mar 04 '18 at 15:23