3

I'm new to Android developing and I would really appreciate some help here.

I'm using a fragment that contains a TextView and I'm using 5 instances of the same MyFragment class.

In the activity, i got a button and a ViewPager, and I need the button to update all the fragment instances content, whenever its clicked.

Here's the Activity

public class MainActivity extends FragmentActivity {

final static String[] CONTENT = {"a", "b"};
ViewPager pager;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    List<MyFragment> fragments = new Vector<MyFragment>();
    for(int i = 0; i < 5; i++){
        MyFragment fragment = new MyFragment(CONTENT);
        fragments.add(fragment);
    }
    PagerAdapter adapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
    pager = (ViewPager) findViewById(R.id.viewpager);
    pager.setAdapter(adapter);

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //method that isn't working
            PagerAdapter adapter = (PagerAdapter)pager.getAdapter();
            for(int i = 0; i < 5; i++){
                MyFragment fragment = (MyFragment) adapter.getItem(i);
                fragment.textView.setText(fragment.content[1]);
            }
        }
    });
}
}

The Fragment

public class MyFragment extends Fragment{

String[] content;
    TextView textView;

public MyFragment(String[] content) {
    this.content = content;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_content, container, false);
    textView = (TextView) view.findViewById(R.id.textView1);
    textView.setText(content[0]);
    return view;
}

}

And the FragmentPagerAdapter

public class PagerAdapter extends FragmentPagerAdapter{

List<MyFragment> fragments;

public PagerAdapter(FragmentManager fm, List<MyFragment> fragments) {
    super(fm);
    this.fragments = fragments;
}

@Override
public Fragment getItem(int arg0) {
    return fragments.get(arg0);
}

@Override
public int getCount() {
    return fragments.size();
}

}

The OnClick method gives me a NullPointerException whenever i try to access a fragment from the adapter which is less than adapter.getCurrentItem() - 1, or more than adapter.getCurrentItem() + 1.

Any idea on how to update all the fragments at the same time?

Thanks in advance.

Helios
  • 33
  • 1
  • 4
  • You could modify the current visible item and then add a `OnPageChangeListener` to the `ViewPager` and update the other child fragments as the user swipes left or right. – user Sep 09 '12 at 18:27
  • 1
    That works quite well. I've implemented the onPageSelected but there's only one problem left which is, when I start scrolling between the pages, until I release the next fragment is not updated. I though it could be solved with the onScrollStateChanged, but nothing so far. Any suggestion? – Helios Sep 10 '12 at 00:12

1 Answers1

2

The easiest way to update those fragments is to use your code and set the number of fragments that the ViewPager holds in memory to the number of total fragments - 1(so all fragments are valid no matter at what page you are). In your case:

pager.setOffscreenPageLimit(4); // you have 5 elements

You can still use the method from my comment with the method onPageScrollStateChanged(so the update will start the moment the user starts swiping) to see when the user is starting to swipe the pager and update the fragments to the left and right of the currently visible fragment, but this will be a bit difficult to get right so I recommend to go with the first option.

Some points regarding your code containing fragments:

If you nest the fragment class make it static so you don't tie it to the activity object. Don't create a constructor for a Fragment besides the default one. If the framework needs to recreate the fragment it will call the default constructor and if it is not available it will throw an exception. For example, try to change the orientation of the phone/emulator and see what happens(this is one of the cases when Android will recreate the fragments). Last, use a custom name for the ViewPager's adapter, you use PagerAdapter which is the name of the super class of FragmentViewPager and it's very confusing for someone reading your code.

If you need to pass data to the Fragment you could use a creation method like the one below:

public static MyFragment newInstance(String text) {
        MyFragment f = new MyFragment();
        Bundle b = new Bundle();
        b.putString("content", text);
        f.setArguments(b);
        return f;
    }

The text will be available in MyFragment by using getArguments().getString("content");

user
  • 86,916
  • 18
  • 197
  • 190
  • Thanks a lot! I will fix these problems. By the way ViewPager was just a arbitrary name I gave to my actual class to post here. Anyway, thanks for pointing it out, I will keep that in mind. Thanks again for all the tips. – Helios Sep 14 '12 at 01:00
  • I'm having trouble with the same fragments. Could you give a hand? If I kill the app with adb, I got an error, coz the f.getArguments returns null. I tried setting these arguments inside the onCreate, onActivityCreated and some other places, but they didn't work. I understand I need to set them, but not really sure where. I would appreciate – Helios Sep 22 '12 at 00:52
  • @Helios First of all you should create a new question and post relevant pieces of code there. I don't fully understand what you're doing, but if you kill the app you need to save the state of the fragment into something permanent(database) or in a `Bundle`(with `onSaveInstanceState`). – user Sep 22 '12 at 07:18
  • @Luksprog i need your help i am not able to set the textview of frgment in fragmentActvity when i am trying to access the textview id it giving me null and i am using viewpager to display six fragments. – Abhijit Chakra Mar 05 '13 at 06:04
  • @Abhijit Please post a new question with the details of your code. It is impossible to help you with just what you said above. – user Mar 05 '13 at 06:29
  • i mean i am not able to set textview of my fragment in fragmentActivity.her ein stackover flow it wont allow me to post a question thats why i am wrtting in comment, – Abhijit Chakra Mar 05 '13 at 06:35