0

Sorry if my question is silly, and my mistake is blatant, but I am now one week into learning java and android dev, so any constructive criticism, even ones that aren't directly related to my question, for my code, would be very welcome!

Thank you for your help, and time in advanced.

My current situation is, that I am trying to determine which page number I'm on in my ViewPager set up. Basically, I have a bunch of 'forms' that are created, which are instances of a "UserFrament.java" fragment. The form collects user input from a few edit texts and on the push of the button, hopefully stores the data, and goes to the next fragment. (I currently think this is working). However, now, I'm trying to determine the current page I'm on, so I can have my 'onClick' method perform a different task if it's on the last viewPage (store all data, put into an intent and then start another activity to do some stuff with the data).

So currently I have this code inside my 'UserFragment.java':

int currentviewnum =  ((FirstFragment) getActivity()).getPager().getCurrentItem();
String pagenum = Integer.toString(currentviewnum);

Now FirstFragment is the activity that set's up the viewPager etc. My adapter is "FragmentAdapter.java" With my current set up when I print the string 'pagenum' to a random textview on each viewPager page, as I swipe to the next page, (or navigate with my button), the number's are just not right. Say I have 5 pages (the user defines how many forms there are) so, FirstFragment receives an intent defining the number of instances it creates.

The number sequence is like "0, 0, 1,2,3" Then as I scroll back it's doing stuff like "3, 2, 3, 2, 1" So I have no idea why it's so stuffed up.

My UserFragment.java:

    package com.example.thinice;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UserFragment extends Fragment {


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.layout_avgcalcform,
                container, false);
        final EditText markc = (EditText)rootView.findViewById(R.id.editTextASSMARK);
        final EditText marktotc = (EditText)rootView.findViewById(R.id.editTextASSTOT);
        final EditText assvalc = (EditText)rootView.findViewById(R.id.editTextASSWORTH);
        int currentviewnum =  ((FirstFragment) getActivity()).getPager().getCurrentItem();
        String pagenum = Integer.toString(currentviewnum);

           TextView tv = (TextView) rootView.findViewById(R.id.avg_testtv);
             tv.setText(pagenum);
        Button b = (Button) rootView.findViewById(R.id.button1);
        b.setOnClickListener( new View.OnClickListener(){

               public void onClick(View v){

        int currentviewnum =  ((FirstFragment)    getActivity()).getPager().getCurrentItem();
                   ((FirstFragment) getActivity()).saveData(new  Question(markc.getText().toString(),marktotc.getText().toString(),assvalc.getText().toString()));
                   ((FirstFragment) getActivity()).getPager().setCurrentItem(currentviewnum+1);



               }
    });
        return rootView;

    }   

}

If you need to see any more of my code, please let me know. But this is really annoying me. So if anybody out there could help me, it would be fantastic! Thank you very much in advanced.

EDIT:MORE CODE FragmentAdapter.java :

     package com.example.thinice;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;

public class FragmentAdapter extends FragmentPagerAdapter{


    private List<Fragment> fragments;



    public FragmentAdapter(FragmentManager fragmentManager, ArrayList<Fragment> fragments) {
        super(fragmentManager);
            this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        //Bundle args = new Bundle();
        //args.putInt("page_position", position+1);
        //((Fragment) fragments).setArguments(args);
        return this.fragments.get(position);
    }

    @Override
    public void destroyItem (ViewGroup container, int position, Object object)
    {
        super.destroyItem(container, position, object);
    }

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

FirstFragment.java (this is my activity) :

    package com.example.thinice;



import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.widget.Button;

public class FirstFragment extends FragmentActivity 
  {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_viewpager);

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        int size = getIntent().getExtras().getInt("numass1");
        ViewPager vp = (ViewPager) findViewById(R.id.viewPager);



            if (savedInstanceState != null) {
                return;
            }

            ArrayList<Fragment> lf = new ArrayList<Fragment>();
            for(int count=0; count<size; count ++){

                Fragment f = new UserFragment();
                lf.add(f);







            }

 FragmentAdapter hello = new FragmentAdapter(getSupportFragmentManager() , lf);
            vp.setAdapter(hello);
          //  vp.setOffscreenPageLimit(size);


        }

    SparseArray<Question> questions = new SparseArray<Question>();
    public void saveData(Question quest){
        ViewPager vp = (ViewPager) findViewById(R.id.viewPager);
           questions.put(vp.getCurrentItem(), quest);

    }
    public ViewPager getPager() {
        ViewPager vp = (ViewPager) findViewById(R.id.viewPager);
        return vp;
    }




    }
Leon92
  • 505
  • 1
  • 9
  • 15

2 Answers2

2

You are getting those wrong numbers because the ViewPager instantiates the fragments surrounding the current one, in order to get a smooth swipe. Using setOffScreenPageLimit(int) you set the number of pages that should be retained to either side of the current page. The default is 1. Also note that the ViewPager first position is 0, not 1.

  1. When you set the ViewPager's adapter and it shows the first page (position=0), the fragment of the second page is also created while the current page position is still 0.
  2. You swipe to the page 2 and the third fragment is created while the current page position is 1.(There is now one exisiting instance to each side of the current one)
  3. swipe to page 3 and the fourth fragment is created showing the current page position, which is now 2. (page 1 fragment is destroyed)
  4. Swipe to page 4 and the last fragment is created while the current page position is 3. (page 2 is destroyed)
  5. Swipe to the page 5 (page 3 is destroyed)

The same when you scroll back, page 5 and page 4 already exist, showing wrong positions 3 and 2, when you swipe back to page 4, fragment in page 3 is created while current position is 3, and so on.

To get the page position. Just like Ramy mentioned, you can get the position from the PagerAdapter's getItem() and pass it as an argument to each instance of UserFragment.

public Fragment getItem(int position) {
    UserFragment fragment = new UserFragment();
    Bundle args = new Bundle();
    args.putInt("page_position", position + 1);
    fragment.setArguments(args);
    return fragment;
}

Then, you can get the position in UserFragment like this:

TextView tv = (TextView) rootView.findViewById(R.id.avg_testtv);
tv.setText(String.valueOf(getArguments().getInt("page_position")));

edit

Try this way:

public Fragment getItem(int position) {
    UserFragment fragment = fragments.get(position);
    Bundle args = new Bundle();
    args.putInt("page_position", position + 1);
    fragment.setArguments(args);
    return fragment;
}
ILovemyPoncho
  • 2,762
  • 2
  • 24
  • 37
  • Hello! Thank you for your help. I have tried to set the offscreenpagelimit. I have set it to the 'size' which is number of forms (this is dynamic, and user defined) ... let's say they want to create 5 forms. However, now the number is always 0. I have changed no code, and have just set the offscreenpagelimit! Do you have any idea what I could change to fix this? – Leon92 Jul 05 '14 at 08:49
  • Sorry, I didn't mean that setting offScreenPageLimit was a solution to your problem, I mentioned it so you can understand what is going on. I'll edit my answer to show you how to get the page position. – ILovemyPoncho Jul 05 '14 at 15:44
  • Yeah, the reason I haven't solved it yet is my code for getItem is fairly different and I'm not sure how to do it. I'll edit my original post so you can see the code in my FragmentAdapter.java so you can better help with the specifics! Thank you :) – Leon92 Jul 06 '14 at 01:01
  • Hrmm. Actually, sorry for this. On a similar note, how do I access my getCount method from FragmentAdapter in my UserFragment (I want to check, if the current page number is the last page, by checking size). Please help me with this! I do not want to open another question? – Leon92 Jul 06 '14 at 09:25
  • UserFragment fragment = fragments.get(position); can you please describe this line. why fragments.get(position) – Milon Apr 11 '16 at 15:45
0

I don`t know why this is sequence of numbers appear like That , But i think i understand what you want to Do . So ,

1) you can modify Fragment By using : setArguments -> say we will use number of page to modify the fragment You can Find SetArguments

[1]: How to use setArguments() and getArguments() methods in Fragments?

2) From FragmentActivity That Hold ViewPager u can use :

      `mViewPager.setOnPageChangeListener(this);mViewPager.getCurrentItem();`

to get current Page Index

3) pass it To Fragment while attaching it FragmentPagerAdapter

@Override
    public Fragment getItem(int position) {
        UserFragment form = new UserFragment();
        Bundle bundl = new Bundle();
        bundl.putString("index", getCurrentPage);
        form.setArguments(bundl);
        return form;
    }

Hope That Help

Community
  • 1
  • 1
Ramy Sabry
  • 378
  • 2
  • 9
  • Hello thank you for your help so far! I'm a little confused on how to set Arguments. To be like the 'size'. So that would be my "UserFragment" file that I edit it in? If you could clarify with a bit more detail on how to fully implement your solution. Thank you very much. – Leon92 Jul 05 '14 at 08:52