In my Fragment i have his code for listener
private FragmentTwoCallBackListener fragmentTwoCallBackListener;
public interface FragmentTwoCallBackListener {
void onItemTypeClick(String itemType,String textInPunjabi);
}
public void onAdapterItemTypeClick(String textA, String textB){
if(fragmentTwoCallBackListener == null)
Log.w(TAG," fragmentTwoCallBackListener Null Error - ");
else
Log.w(TAG," fragmentTwoCallBackListener not Null - " );
fragmentTwoCallBackListener.onItemTypeClick(textInEnglish,textInPunjabi);
}
on normal usage the app is working fine. but when App is Resume I got this error
java.lang.NullPointerException: at com.shayari4u.punjabistatus.FragmentTwo.onAdapterItemTypeClick (FragmentTwo.java:133) at com.shayari4u.punjabistatus.FragmentTwoAdapter$1.onClick (FragmentTwoAdapter.java:115)
after many Hit & Try I found that on App Resume the fragmentTwoCallBackListener object is null
Im using this fragment in TabbedLayout.
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
f1 = new FragmentOne();
if (getIntent().hasExtra("type")) { // PUT EXTRAS FOR FRAGMENT IF GET NOTIFICATION
Bundle bundle = new Bundle();
bundle.putString("post_type", getIntent().getStringExtra("type"));
f1.setArguments(bundle);
Log.w(TAG,"Tabbed Activety Get Notification for Post Type - " + getIntent().getStringExtra("type"));
}
showItemFragment = new FragmentTwo();
showItemFragment.setFragmentTwoCallBackListener(this);
adapter.addFragment(showItemFragment, "Category");
adapter.addFragment(f1, "Posts");
if(adapter==null){
Log.w("Tabbed","Adapter is blank");
}{
viewPager.setAdapter(adapter);
}
}
How to solve this problem plz help
Under numerous circumstances, the Android framework will kill your app's process to save system resources. When this happens, your app is given a chance to save its state so that it can be restored when the user eventually navigates back to your app.
Anything that you don't store using this process will be lost.
Activities, Fragments, and Views all have some built-in capability to save their state when this happens. Often this is a good thing, but here it is going to make your life harder. When the system destroys your app and recreates it, since the fragment manager will successfully save and restore your fragments, your
setupViewPager()
method won't be called again.Since your fragment doesn't have a way to save its
FragmentTwoCallBackListener
, and sincesetupViewPager()
won't be called again to re-set it, it will benull
when this happens.One way to solve this is to change how your
FragmentTwoCallBackListener
instance is obtained. Perhaps rather than using a setter, you could do something like this in your fragment: