I have a ViewPager, and there's a button when clicked, deletes the current fragment from the PagerAdapter, and prevents the user from swiping there. I researched and found this Remove Fragment Page from ViewPager in Android to be the closest to what I want.
In my fragment to be deleted:
#Override
public void onClick(View v) {
db.delete(count); //SqliteDatabase deletion
displayActivity.removeCurrentFragment(0);
}
My PagerAdapter
public class PagerAdapter extends FragmentPagerAdapter {
long baseId = 0;
public static List<Fragment> fragmentArrayList = new ArrayList<Fragment>();
public PagerAdapter(FragmentManager fm){
super(fm);
fragmentArrayList.add(new FragmentOne());
fragmentArrayList.add(new FragmentTwo());
fragmentArrayList.add(new FragmentThree());
}
#Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
}
#Override
public int getCount() {
return fragmentArrayList.size();
}
#Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
#Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
}
This is the activity (DisplayActivity) that hosts the pagerAdapter
public class DisplayActivity extends AppCompatActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_layout);
viewPager = (ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public void removeCurrentFragment(int position){
pagerAdapter.fragmentArrayList.remove(position);
pagerAdapter.notifyDataSetChanged();
}
What did I do wrong here?
I'm getting an error of
.removeCurrentFragment(int)' on a null object reference
So this error suggests that my method call removeCurrentFragment is referencing a null object, how do I fix it?
You have used
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
so you are creating a new local variable instead of using your global variable. Instead change your line as
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
It should work.
Your onCreate method should look like this.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_layout);
viewPager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
Related
I have an android app with TabLayout , I create TabItems and assign them to my TabLayout Dynamically with code in my MainActivity , in one of my Fragments, which is the Fragment for a TabItem , i have a button . what I want is when that button is clicked, its TabItem closes and destroys, how can I achieve that?
extra explanation: bellow is my MainActivity.java Code ( where most of my code for creating dynamic TabItems exists :
public class MainActivity extends AppCompatActivity implements ContactsFragment.CallBacks {
public static List<Fragment> fragments = new ArrayList<>();
public static List<String> fragmentsTitle = new ArrayList<>();
ViewPager viewPager;
TabLayout tabLayout;
public List<Fragment> getFragments() {
return fragments;
}
public List<String> getFragmentsTitle() {
return fragmentsTitle;
}
public void addToFragments(Fragment fragment) {
fragments.add(fragment);
}
public void addToFragmentsTitle(String title) {
fragmentsTitle.add(title);
}
public Fragment getFragmentsWithPosition(int position) {
return fragments.get(position);
}
public String getFragmentsTitleWithPosition(int position) {
return fragmentsTitle.get(position);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_drawer);
this.tabLayout = findViewById(R.id.tab_layout);
this.viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
SetUpViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public void SetUpViewPager(ViewPager viewPager) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter((getSupportFragmentManager()));
Adapter.AddFragmentPage(new SignInFragment(),"ورود");
Adapter.AddFragmentPage(new ContactsFragment(),"ارتباطات");
Adapter.AddFragmentPage(new RegisterFragment(),"ثبت نام");
viewPager.setAdapter(Adapter);
}
#Override
public void send_user_object() {
/* this is the implementation of abstract function defined
in one of my tab , in which it has a button and when
button is clicked i want the tab to be removed . */
}
public class MyViewPagerAdapter extends FragmentPagerAdapter {
public MyViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void AddFragmentPage(Fragment frag,String title) {
MainActivity.this.addToFragments(frag);
MainActivity.this.addToFragmentsTitle(title);
}
public Fragment getItem(int position) {
return MainActivity.this.getFragmentsWithPosition(position);
}
public CharSequence getPageTitle(int position) {
return MainActivity.this.getFragmentsTitleWithPosition(position);
}
public int getCount() {
List<Fragment> frag = MainActivity.this.getFragments();
return frag.size();
}
}
}
in one of my predefined tabs , i have a listview , when user clickes on an item on the list view , the detail of the item opens in a new tab , then user can see the detail by clicking on that tab . what i want is how user can close ( destroy ) that detail tab about one of items ? ( remember it is creating dynamically )
how can I remove ( close ) the TabItem with Click of a Button in that TabItem Fragment?
Plase help me , thank you beforehand .
It's not a good practice to change horizontal navigation by adding another fragment. If it's not absolutely required by your customer, create a new fragment and just replace the current one like this:
Fragment detailsFragment=new ContactsFragment()
getSupportFragmentManager.beginTransaction()
.addToBackStack("tag")
.replace(R.id.containerName, detailsFragment, "another_tag")
.commit()
At your detailsFragment your close button's clickListener just call getActivity.getSupportFragmentManager.popBackStack()
and it restores previous state.
Hope I could help you.
I solved my problem by :
first ) creating an interface in the UserDetailFragment, which you all know for communication with MainActivity, I had to do that.
but for what did I need communicating with the MainActivity ?
Answer : as you see in my code , my FragmentPagerAdapter class is defined there , and i needed my public List<Fragment> fragments = new ArrayList<>(); and public static List<String> fragmentsTitle = new ArrayList<>(); that i had saved my fragments into them , and also mytabLayout.
Seconde ) i had to define tabLayout.addOnTabSelectedListener(){} with its method OnTabSelected() , i needed that because i get the current index of the tab using addOnTabSelectedListener(){} .
Third ) i defined removeTabPage(int position) in the FragmentPagerAdapter .
Forth ) i created a method as bellow ( which is the implementation of the abstract method of UserDetailFragment interface.
#Override
public void close_tabitem() {
tabLayout.removeTabAt(tabposition_number);
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.removeTabPage(tabposition_number);
Adapter.notifyDataSetChanged();
}
and here is my whole code for: MainActivity.Java
public class MainActivity extends AppCompatActivity implements ContactsFragment.CallBacks, UserDetailFragment.DetailCallBacks {
android.support.v7.widget.Toolbar toolbar;
public static List<Fragment> fragments = new ArrayList<>();
public static List<String> fragmentsTitle = new ArrayList<>();
ViewPager viewPager;
TabLayout tabLayout;
int tabposition_number;
public List<Fragment> getFragments() {
return fragments;
}
public List<String> getFragmentsTitle() {
return fragmentsTitle;
}
public void addToFragments(Fragment fragment) {
fragments.add(fragment);
}
public void addToFragmentsTitle(String title) {
fragmentsTitle.add(title);
}
public Fragment getFragmentsWithPosition(int position) {
return fragments.get(position);
}
public String getFragmentsTitleWithPosition(int position) {
return fragmentsTitle.get(position);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_drawer);
this.tabLayout = findViewById(R.id.tab_layout);
this.viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
SetUpViewPager(viewPager);
this.toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = findViewById(R.id.navigation_view);
navigationView.setItemIconTintList(null);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabposition_number = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public void SetUpViewPager(ViewPager viewPager) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter((getSupportFragmentManager()));
Adapter.AddFragmentPage(new SignInFragment(),"ورود");
Adapter.AddFragmentPage(new ContactsFragment(),"ارتباطات");
Adapter.AddFragmentPage(new RegisterFragment(),"ثبت نام");
viewPager.setAdapter(Adapter);
}
#Override
public void send_user_object(UserObject userObject) {
// tabLayout.removeTabAt(tabposition_number);
// myViewPagerAdapter.remove
}
#Override
public void create_user_detail_tab(UserObject userObject) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
UserDetailFragment userDetailFragment = new UserDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("name",userObject.getName());
bundle.putString("family",userObject.getFamily());
bundle.putString("email",userObject.getEmail());
userDetailFragment.setArguments(bundle);
Adapter.AddFragmentPage(userDetailFragment,userObject.getName());
viewPager.setAdapter(Adapter);
}
#Override
public void close_tabitem() {
tabLayout.removeTabAt(tabposition_number);
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.removeTabPage(tabposition_number);
Adapter.notifyDataSetChanged();
}
public class MyViewPagerAdapter extends FragmentPagerAdapter {
public MyViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void removeTabPage(int position) {
fragments.remove(position);
fragmentsTitle.remove(position);
notifyDataSetChanged();
}
public void AddFragmentPage(Fragment frag,String title) {
MainActivity.this.addToFragments(frag);
MainActivity.this.addToFragmentsTitle(title);
}
public Fragment getItem(int position) {
return MainActivity.this.getFragmentsWithPosition(position);
}
public CharSequence getPageTitle(int position) {
return MainActivity.this.getFragmentsTitleWithPosition(position);
}
public int getCount() {
List<Fragment> frag = MainActivity.this.getFragments();
return frag.size();
}
}
}
and here is the UserDetailFragment.Java , which acts as my TabItem :
public class UserDetailFragment extends Fragment {
View view;
DetailCallBacks detailCallBacks;
public UserDetailFragment() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.user_detail_fragment,null);
return view;
}
#Override
public void onResume() {
super.onResume();
Button closebtn = view.findViewById(R.id.detail_close_button);
closebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detailCallBacks.close_tabitem();
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
detailCallBacks = (DetailCallBacks)context;
}
public interface DetailCallBacks {
public void close_tabitem();
}
}
Hope It Helps You.
But do remember, you can not use this button. put the button in some other tabitem or in the menu.
or you can use :
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();
to change the tabitem and then fire the event .
enjoy .....
there is a fragment in my activity in which there is a viewpager which has 5 fragments in it and inside the main activity i need to get one of the fragment from viewpager
Activity
public class MainActivity extends AppCompatActivity {
public void setFragment(){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mainFragment= new MainFragment();
FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, mainFragment,"mainFragment");
fragmentTransaction.commitAllowingStateLoss();
}
}, 250);
}
public void findFragment() {
mainFragment= (MainFragment) getSupportFragmentManager().findFragmentByTag("mainFragment");
viewPager = mainFragment.viewPager;
FragmentOne fragment = (FragmentOne) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + viewPager.getCurrentItem());
}
}
MainFragment
public class MainFragment extends Fragment{
private void initViewPagerAndTabs() {
viewPager = view.findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getChildFragmentManager());
pagerAdapter.addFragment(FragmentOne.newInstance(), "one");
pagerAdapter.addFragment(FragmentTwo.newInstance(), "two");
pagerAdapter.addFragment(FragmentThree.newInstance(), "three");
pagerAdapter.addFragment(FragmentFour.newInstance(), "four");
pagerAdapter.addFragment(FragmentFive.newInstance(), "five");
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = view.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);
viewPager.setOffscreenPageLimit(3);
}
private static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
private PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
if i use "getFragmentManager()" instead of "getChildFragmentManager()" then it returns the fragment but when i use "getChildFragmentManager()" in viewPager it returns null in activity
Try this Running Code for 1 fragment, may it helps you in your code :
Main Activity
public class OpenQuran extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
TabLayout tabLayoutqaue;
Pager mAdapter;
MediaPlayer mp;
//This is our viewPagerss
ViewPager viewPager;
View mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_quran);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Read Quran");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Initializing the tablayout
tabLayoutqaue = (TabLayout) findViewById(R.id.tabLayoutqaue);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
mAdapter = new Pager(getSupportFragmentManager());
// 1 Fragment
mAdapter .addFrag(new Quran(), "Quran");
viewPager.setAdapter(mAdapter);
tabLayoutqaue.setupWithViewPager(viewPager);
tabLayoutqaue.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
Fargment Class :
public class parahlist extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.activity_parahlist, container, false);}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
View Pager Class:
public class Pager extends FragmentPagerAdapter {
//integer to count number of tabs
int tabCount;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
//Constructor to the class
public Pager(FragmentManager fm) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment Fragment, String title) {
mFragmentList.add(Fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Now This the code Of MainActivity, 2nd Fragment and 3rd one is View Pager class. You dont need to change or edit your View Pager Class. Just Create Java Class and Paste that code as it is.
In Main Activity the Line : mAdapter .addFrag(new Quran(), "Quran"); adding description and Fragment. You can add your own fragment after "new".
After that you have to put Tablayout widget in you Xml as Follows:
<android.support.design.widget.TabLayout
android:id="#+id/tabLayoutqaue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorgreen"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#color/colorback"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
And View Pager like:
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
/>
You may face some issue regarding tablayout :
Just put this line in your gradle build under dependecies:
compile 'com.android.support:design:25.3.1'
According to your version. for example you have 25.0.1
then line will be :
compile 'com.android.support:design:25.0.1
Still i m here to tell you more. if you got problem!
My goal is to delete a fragment from a ViewPager upon user button click.
Populating the ViewPager works fine, but when I try to delete it, I get an error indicating a null reference. I incorporated Remove Fragment Page from ViewPager in Android
In my fragment to be deleted I have:
Button delete = (Button) getActivity().findViewById(R.id.dont_show_button_1);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.deletePerson(count); // SQLiteDatabase, works fine
displayActivity.removeCurrentFragment(count-1);
}
});
DisplayActivity is as follows:
public class DisplayActivity extends FragmentActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
String TAG = "DisplayActivity";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_layout);
viewPager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public void removeCurrentFragment(int position){
pagerAdapter.fragmentArrayList.remove(position);
pagerAdapter.notifyChangeInPosition(1);
pagerAdapter.notifyDataSetChanged();
Log.e(TAG, "in removeCurrentFragment");
}
}
PagerAdapter
public class PagerAdapter extends FragmentPagerAdapter {
long baseId = 0;
public static List<Fragment> fragmentArrayList = new ArrayList<Fragment>();
public PagerAdapter(FragmentManager fm){
super(fm);
fragmentArrayList.add(new FragmentOne());
fragmentArrayList.add(new FragmentTwo());
fragmentArrayList.add(new FragmentThree());
}
#Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
#Override
public int getCount() {
return fragmentArrayList.size();
}
#Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
#Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
* #param n number of items which have been changed
*/
public void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
}
This is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void .DisplayActivity.removeCurrentFragment(int)' on a null object reference
Triggered from the fragment
Edit:
public class FragmentOne extends Fragment {
DatabaseHelper db;
WebView mWebView;
DisplayActivity displayActivity;
int count = 1;
This is how I get reference from displayActivity, is this the wrong way to get a reference of it?
if (count > 0) {
displayActivity.removeCurrentFragment(count - 1);
}
My ViewPager will delete a fragment upon button click. But when I click delete, I get "canot change tag" error. Browsing through other similar questions, it was either a problem with the getItem, or getCount in the PagerAdapter, which I think my implementation is fine. Please advice.
This is the fragment to be deleted
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
displayActivity = (DisplayActivity) getActivity();
initView();
}
Button delete = (Button) getActivity().findViewById(R.id.dont_show_button_1);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayActivity.removeCurrentFragment(count-1);
}
});
My PagerAdapter is
public class PagerAdapter extends FragmentPagerAdapter {
long baseId = 0;
public static List<Fragment> fragmentArrayList = new ArrayList<Fragment>();
public PagerAdapter(FragmentManager fm){
super(fm);
fragmentArrayList.add(new FragmentOne());
fragmentArrayList.add(new FragmentTwo());
fragmentArrayList.add(new FragmentThree());
}
#Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
#Override
public int getCount() {
return fragmentArrayList.size();
}
#Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
#Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
* #param n number of items which have been changed
*/
public void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
}
This is the activity that hosts the ViewPager
public class DisplayActivity extends FragmentActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
String TAG = "DisplayActivity";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_layout);
viewPager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public void removeCurrentFragment(int position){
pagerAdapter.fragmentArrayList.remove(position);
pagerAdapter.notifyChangeInPosition(1);
pagerAdapter.notifyDataSetChanged();
Log.e(TAG, "in removeCurrentFragment");
}
I'm getting the error:
IllegalStateException: Can't change tag of fragment FragmentTwo{170c98f1 #1 id=0x7f0c006d android:switcher:2131492973:1}: was android:switcher:2131492973:1 now android:switcher:2131492973:3
The problem was with
public class PagerAdapter extends FragmentPagerAdapter
Changing it to
public class PagerAdapter extends FragmentStatePagerAdapter
enabled correct deletion.
This can be attributed to "FragmentStatePagerAdapter disposes of views that fall outside the current and traversable views."
As suggested to this post
Remove Fragment Page from ViewPager in Android
By Looking at your code i think your count value may be wrong.
Button delete = (Button) getActivity().findViewById(R.id.dont_show_button_1);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// here
displayActivity.removeCurrentFragment(count-1);
//change to
displayActivity.removeCurrentFragment(adapter.getCount()-1);
}
});
Hope it helps.Please post your whole code like where you getting the value of count variable. Post whole Code if Solution Does not Solve Your Problem .
Refer here for example:- https://androidruler.wordpress.com/2016/02/22/working-with-viewpager-as-a-images-slider/
I have a viewpager with 2 fragment pages inside it. Now i want to access the views (textview,buttons) from the first fragment page but everytime Iam getting Nullpointer exception
check out my code
Fragment i want to access its views:
public class ListPagerFragment extends Fragment
{
ListView listview;
TextView text;
private ViewPager pager;
public static ListPagerFragment newInstance(int message)
{
ListPagerFragment f = new ListPagerFragment();
// pass the text message received from main activity into a bundle to be
// delivered to the new fragment
Bundle bdl = new Bundle();
bdl.putInt("num", message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.list_pager_fragment, container, false);
return v;
}
public void fillList(Nameslist list)
{
listview = (ListView) getView().findViewById(R.id.listView1);
if (listview == null)
System.out.println("listview null"); //this should not be null but
//it is thus the nullpointerexception
if (listview.getAdapter() == null)
{
MyListAdapter listAdapter = new MyListAdapter(getActivity(), R.layout.listview_item, list.getVenues());
listview.setAdapter(listAdapter);
}
else
{
((MyListAdapter) listview.getAdapter()).updateAdapter(list.getnames());
}
}
PagerAdapter code
public class MyPagerAdapter extends FragmentStatePagerAdapter
{
private int mCount = 1;
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 1:
return ResultsPagerFragment.newInstance(position);
}
return ListPagerFragment.newInstance(position);
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return mCount;
}
}
and main finally activity code
private ViewPager pager;
private MyPagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
}
and later somewhere in the activity i have the code that should trigger the fillList from Fragment to do the job
Fragment frag = pagerAdapter.getItem(0); //this should give me the Fragment i want right?
((ListPagerFragment)frag).fillList(result);
What am I missing here?
Ok I found it seems like the problem was in my custom FragmentStatePagerAdapter
All I had to do is create the fragments when activity is created and put them into an ArrayList which it will be later passed to MyPagerAdapter
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
frags = new ArrayList<Fragment>();
frags.add(ListPagerFragment.newInstance(0));
frags.add(ResultsPagerFragment.newInstance(1));
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(),frags);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
}
And then modify the MyPagerAdapter like so:
public class MyPagerAdapter extends FragmentStatePagerAdapter
{
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm, List<Fragment> frags)
{
super(fm);
this.fragments = frags;
}
#Override
public Fragment getItem(int position)
{
return fragments.get(position);
}
}
kind of silly isn't it? I don't understand the point but it worked
That's probably because you are trying to use the views from your Activity, before your ListPagerFragment.onCreateView() has inflated your xml layout. Move what's inside your onCreate() and some code of fillList() to onCreateView(), something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_pager_fragment, container, false);
listview = (ListView) v.findViewById(R.id.listView1);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
return v;
}
After your fragments onCreateView() has inflated the view, you can try to fill it.
And don't forget to clear your view references and unregister your listview listener(if you set one) in onDestroyView() to avoid memory leaks, e.g.
#Override
public void onDestroyView() {
super.onDestroyView();
listview.setOnItemClickListener(null);
...
listview = null;
}
read about the fragment's lifecycle --> Fragment's Lifefycle