Dodi
Dodi

Reputation: 2269

update Fragment after AsyncTask finishes

I have an activity that hosts 2 tabs fragments. I fetch some data from database and based on that I want to update textviews inside my 2 tab fragments after AsyncTask finishes. However I get java.lang.NullPointerException at computing.gmit.ie.scorerapp.Team1Fragment.update(Team1Fragment.java:36) when I try to update the view inside the fragment. This is the code:

public class Tabs extends FragmentActivity implements ActionBar.TabListener {

    private static final String SERVER_ROOT_URI_CYPHER = "xxxxxx";
    private Map<String, List<String>> map = new HashMap<>();
    ActionBar actionBar;
    ActionBar.Tab tab1;
    ActionBar.Tab tab2;
    ViewPager viewPager;
    private List<String> teamList;
    // list of players team 1
    private List<String> team1Players = new ArrayList<>();
    // list of players team 2
    private List<String> team2Players = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabs);

        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                getActionBar().setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });



        actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        tab1 = actionBar.newTab();
        tab1.setText("Tab 1 ");
        tab1.setTabListener(this);

        tab2 = actionBar.newTab();
        tab2.setText("Tab 2");
        tab2.setTabListener(this);

        actionBar.addTab(tab1);
        actionBar.addTab(tab2);

        //execute async task here
        TeamPlayer teamPlayer = new TeamPlayer();
        teamPlayer.execute();

    }

My adapter

class MyAdapter extends FragmentPagerAdapter {

        MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragement = null;
            if (position == 0) {
                fragement = new Team1Fragment();
            } else {
                fragement = new Team2Fragment();
            }
            return fragement;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }

My async task -->> null here

private class TeamPlayer extends AsyncTask<Void, Void, Void> {

Team1Fragment frg = new Team1Fragment();

@Override
protected Void doInBackground(Void... params) {
    try {
        getPlayersAndTeams(SERVER_ROOT_URI_CYPHER);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

@Override
protected void onPostExecute(Void aVoid) {

    // title of the tabs
    tab1.setText(teamList.get(0));
    tab2.setText(teamList.get(1));

    frg.update();   ------> null 

}
}

My fragment

public class Team1Fragment extends Fragment {

    TextView textView;


    public Team1Fragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_team1, container, false);
        textView = (TextView) view.findViewById(R.id.tvTeam1Fragment);

        return view;
    }

    public void update(){
        textView.setText("HELLOOOO");
    }

}

Upvotes: 2

Views: 1258

Answers (1)

einschnaehkeee
einschnaehkeee

Reputation: 1888

Team1Fragment frg = new Team1Fragment();

That's your problem. The only time you instantiate a new fragment when using it with a pager adapter is inside the getItem() method, never anywhere else. Please refer to the Android samples regarding fragments inside a pager with an actionbar. If you did that, make sure you implement everything correctly and then you can do async stuff.

Regarding your main problem:

If you want to update your fragment from an async task, attach your fragment to the task by reference and then update it, if its still attached to the activity.

Regarding the implementation: If your task resides inside your activity, you notify your activity from within your fragments (use getActivity() inside onAttach() or onViewReady()), then the activity can start the task and attach the fragments to the tasks.

It's better to abstract the whole mechanism with interfaces, so the task doesn't really know about fragments, but about subscribers, which implement the interface TeamDataSubscriber (or something like that) and get the data. A setSubscribers(TeamDataSubscribers... subs) is needed, etc .you hopefully know that stuff.

Upvotes: 1

Related Questions