-1

Preface: I'm very new to Android. I've looked around, read numerous tutorials and I'm still not grasping the concept here. I will apologize in advance if it is something simple.

I have an activity that is implementing a FragmentPagerAdapter using boilerplate code from the template in Android Studio. My goal is to switch between various instances of the same fragment to track player scores (i.e., same layout, different scores in each). Currently, I am able to switch between what looks to be various fragments. I am able to click buttons on the first fragment to computer the score, but when I switch over to the next fragment and click a button, nothing happens in that fragment but the first fragment's score changes. I think this is because it is only using one fragment and not the 7 that I need. If you could help me figure out how to keep scores saved to each fragment and that the buttons on, say fragment2, only change scores on fragment2.

Here is what I have so far:

    package com.brbecker.tabletopcompanion.Games;


import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.brbecker.tabletopcompanion.MainActivity;
import com.brbecker.tabletopcompanion.R;

public class SwipeActivity extends Activity {
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    // Supposed to be able to create multiple fragment instances and get at them again later.
    private SwipeTestFragment player1, player2, player3, player4, player5, player6, player7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swipe);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_swipe, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Then the FragmentPagerAdapter class

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a SwipeTestFragment.

        return SwipeTestFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 7 total pages.
        return 7;
    }

    // This method is supposed to save a reference to a created Fragment.
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
        switch (position) {
            case 0:
                player1 = (SwipeTestFragment) createdFragment;
                break;
            case 1:
                player2 = (SwipeTestFragment) createdFragment;
                break;
            case 2:
                player3 = (SwipeTestFragment) createdFragment;
                break;
            case 3:
                player4 = (SwipeTestFragment) createdFragment;
                break;
            case 4:
                player5 = (SwipeTestFragment) createdFragment;
                break;
            case 5:
                player6 = (SwipeTestFragment) createdFragment;
                break;
            case 6:
                player7 = (SwipeTestFragment) createdFragment;
                break;
        }
        return createdFragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "PLAYER 1";
            case 1:
                return "PLAYER 2";
            case 2:
                return "PLAYER 3";
            case 3:
                return "PLAYER 4";
            case 4:
                return "PLAYER 5";
            case 5:
                return "PLAYER 6";
            case 6:
                return "PLAYER 7";
        }
        return null;
    }
}

Then the Fragment Code:

public class SwipeTestFragment extends Fragment implements View.OnClickListener {

    // The fragment argument representing the section number for this fragment.
    private static final String ARG_SECTION_NUMBER = "section_number";

    public SwipeTestFragment() {
    }

    // Returns a new instance of this fragment for the given section number.
    public static SwipeTestFragment newInstance(int sectionNumber) {
        SwipeTestFragment fragment = new SwipeTestFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setRetainInstance(true);
        View rootView = inflater.inflate(R.layout.fragment_swipe, container, false);

        //Set Page Title
        TextView playerHeading = (TextView) rootView.findViewById(R.id.playerHeading);
        String playerHeadingString = "Player " + getArguments().getInt(ARG_SECTION_NUMBER);
        playerHeading.setText(playerHeadingString);

        //This section sets up buttons.
        ImageButton minusone = (ImageButton) rootView.findViewById(R.id.minusBtn1);
        minusone.setOnClickListener(this);
        ImageButton plusone = (ImageButton) rootView.findViewById(R.id.plusBtn1);
        plusone.setOnClickListener(this);

        return rootView;
    }

    @Override
    public void onClick(View v) {
        TextView score = (TextView) getActivity().findViewById(R.id.scoreSevenWonders);
        TextView coins = (TextView) getActivity().findViewById(R.id.coinsSevenWonders);

        switch (v.getId()) {
            case R.id.minusBtn1:
                String presentvaluestring = coins.getText().toString();
                if (Integer.parseInt(presentvaluestring) > 0) {
                    int presentvalueint = Integer.parseInt(presentvaluestring);
                    presentvalueint--;
                    coins.setText(String.valueOf(presentvalueint));
                    if (presentvalueint % 3 == 2) {
                        setPlayerScore(-1, score);
                    }
                }
                break;
            case R.id.plusBtn1:
                presentvaluestring = coins.getText().toString();
                int presetvalueint = Integer.parseInt(presentvaluestring);
                presentvalueint++;
                if ((presentvalueint % 3) == 0) {
                    setPlayerScore(1, score);
                }
                coins.setText(String.valueOf(presentvalueint));
                break;                
        }
    }

    public TextView setPlayerScore(int increment, TextView total) {
        String totalstring = total.getText().toString();
        int totalint = Integer.parseInt(totalstring); //see if Integer.parseInt(total.getText().toString()) will work
        totalint += increment;
        total.setText(String.valueOf(totalint));
        return total;
    }
}

I think it has something to do with the getItem() method, but I'm not sure. I am more than happy to provide additional code if necessary.

brbecker87
  • 40
  • 11

1 Answers1

0

SwipeActivity.java

package com.brbecker.tabletopcompanion.Games;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.brbecker.tabletopcompanion.MainActivity;
import com.brbecker.tabletopcompanion.R;

public class SwipeActivity extends Activity  implements View.OnClickListener{
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    int[] scoresVal = new int[7];
    int[] coinsVal = new int[7];
    int current_pos = 0;
    TextView score;
    TextView coins;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swipe);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    score = (TextView) findViewById(R.id.scoreSevenWonders);
    coins = (TextView) findViewById(R.id.coinsSevenWonders);

    ImageButton minusone = (ImageButton) findViewById(R.id.minusBtn1);
    minusone.setOnClickListener(this);
    ImageButton plusone = (ImageButton) findViewById(R.id.plusBtn1);
    plusone.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.minusBtn1:
                 int pos = viewpager.getCurrentItem();
                 presentvalueint = coinsVal[pos];
                 presentvalueint--;
                 if (presentvalueint % 3 == 2) {
                    score.setText(setPlayerScore(-1, pos));
                 }
                 coinsVal[pos] = presentvalueint;
                 coins.setText(String.valueOf(presentvalueint));
            break;
            case R.id.plusBtn1:
                 int pos = viewpager.getCurrentItem();
                 presentvalueint = coinsVal[pos];
                 presentvalueint++;
                 if (presentvalueint % 3 == 2) {
                     score.setText(setPlayerScore(-1, pos));
                 }
                 coinsVal[pos] = presentvalueint;
                 coins.setText(String.valueOf(presentvalueint));
            break;                
        }
    }

public String setPlayerScore(int increment, int pos) {


        scoresVal[pos] += increment;
        return String.valueOf(scoresVal[pos]);

}   


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_swipe, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

SectionsPagerAdapter.java

public class SectionsPagerAdapter extends FragmentPagerAdapter {


    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a SwipeTestFragment.

        return SwipeTestFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 7 total pages.
        return 7;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "PLAYER 1";
            case 1:
                return "PLAYER 2";
            case 2:
                return "PLAYER 3";
            case 3:
                return "PLAYER 4";
            case 4:
                return "PLAYER 5";
            case 5:
                return "PLAYER 6";
            case 6:
                return "PLAYER 7";
        }
        return null;
    }
}

SwipeTestFragment.java

public class SwipeTestFragment extends Fragment{

// The fragment argument representing the section number for this fragment.
private static final String ARG_SECTION_NUMBER = "section_number";

public SwipeTestFragment() {
}

// Returns a new instance of this fragment for the given section number.
public static SwipeTestFragment newInstance(int sectionNumber) {
    SwipeTestFragment fragment = new SwipeTestFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    setRetainInstance(true);
    View rootView = inflater.inflate(R.layout.fragment_swipe, container, false);

    //Set Page Title
    TextView playerHeading = (TextView) rootView.findViewById(R.id.playerHeading);
    String playerHeadingString = "Player " + getArguments().getInt(ARG_SECTION_NUMBER);
    playerHeading.setText(playerHeadingString);


        return rootView;
    }

}
ugur
  • 3,604
  • 3
  • 26
  • 57
  • Am I correct in assuming that you mean for me to move the line: `TextView score = (TextView) findViewById(R.id.scoreSevenWonders);` from the fragment class (where it is currently written) to the activity class? – brbecker87 Jul 10 '16 at 15:59
  • I chose to override the instantiateItem() method in order to try and save a reference to each of the various versions of fragments that way I could access them later. Is there another way to do that? – brbecker87 Jul 10 '16 at 16:01
  • you dont need to get a reference to any fragment just get the current position of the fragment. so update arrays accordingly. and in your code you use TextView score = (TextView) getActivity().findViewById(R.id.scoreSevenWonders); which means textview is in your activity. so you can move it to activity class in my example. – ugur Jul 10 '16 at 16:19
  • Thanks for sticking with me on this. All of the TextViews and Buttons are in the fragment that is inflated into the container on the activity. I tried moving that line of code to the activity, but the onClick method of the fragment breaks. If it matters, the fragment and activity classes are two separate files... – brbecker87 Jul 10 '16 at 17:21
  • Code throws an error that score.setText() in onClick isn't able to access score TextView. – brbecker87 Jul 10 '16 at 19:35
  • I am and I really appreciate the time. I've made the edits you suggested but now I'm getting a NullPointerException at the `minusone.setOnClickListener(this);` line. – brbecker87 Jul 12 '16 at 00:51
  • Because minusBtn1 and plusBtn1 are in fragment layout xml. Move them to activity layout xml – ugur Jul 12 '16 at 10:39