Question

Could be this is a dupe, but I've been looking for solutions and they always slightly differ from my problem.

So: I'm currently creating an app that has 2 fragments that are swipeable. TaskGroupFragment shows a list and when you click on an item it wil slide to TasksFragment and show you a sublist. What I have to do now is send the id of the selected item from groups to tasks so I can get the sublist out of SQLite.

I know I'm supposed to communicate through the connected MainActivity and I'm already at the point that I've created an interface in TaskGroupsFragment and implemented this in the activity. Tried and tested and the activity receives the TaskGroupID.

The part where I'm stuck is getting this info in TasksFragment. Especially using swipeview makes this harder.

My code:

MainPagerAdapter:

public class MainPagerAdapter extends FragmentStatePagerAdapter {

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

    @Override
    public Fragment getItem(int i) {
        switch (i) {
            case 0: return TaskGroupFragment.newInstance();
            case 1: return TasksFragment.newInstance();
            default: return TaskGroupFragment.newInstance();
        }
    }

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

TaskGroupActivity (sending fragment):

    public class TaskGroupFragment extends ListFragment {

    private DoItDataSource dataSource;
    private List<TaskGroups> groups;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_group, container, false);

        dataSource = new DoItDataSource(getActivity());

        dataSource.open();
        JSONContainer jsonContainer = dataSource.sqliteToContainer();
        dataSource.close();

        groups = jsonContainer.getTask_groups();

        TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
        setListAdapter(adapter);

        return view;
    }

    public static TaskGroupFragment newInstance() {
        TaskGroupFragment tgf = new TaskGroupFragment();
        return tgf;
    }

    public interface OnTaskGroupSelectedListener {
        public void onTaskGroupSelected(String taskGroupId);
    }

    OnTaskGroupSelectedListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnTaskGroupSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " Interface not implemented in activity");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {

        ((MainActivity)getActivity()).setCurrentItem(1, true);
        mListener.onTaskGroupSelected(groups.get(position).getId());
    }
}

MainActivity:

public class MainActivity extends FragmentActivity  implements
        TaskGroupFragment.OnTaskGroupSelectedListener{
    private SharedPreferences savedValues;
    private DoItDataSource dataSource = new DoItDataSource(this);

    private String identifier, user, domain;

    private JSONContainer containerToday;
    private JSONContainer containerTomorrow;

    public ViewPager pager;

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

        savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
        identifier = savedValues.getString("Identifier", "");

        pager = (ViewPager) findViewById(R.id.activity_main_pager);
        pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));

        if (identifier == null || identifier.equals("")) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("APP_ID", APP_ID);
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        identifier = savedValues.getString("Identifier", "");
        user = savedValues.getString("User", "");
        domain = savedValues.getString("Domain", "");
        boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);

        //
        // getting lists
        //
    }

    private void resultHandling(String json, String day) {
        if (day.equals("today")) {
            Gson gson = new Gson();
            containerToday = gson.fromJson(json, JSONContainer.class);
            jsonToSQLite(containerToday, "Today");


        } else if (day.equals("tomorrow")) {
            Gson gson = new Gson();
            containerTomorrow= gson.fromJson(json, JSONContainer.class);
            jsonToSQLite(containerTomorrow, "Tomorrow");
        }
    }

    String taskGroupId = "";

    @Override
    public void onTaskGroupSelected(String taskGroupId) {
        this.taskGroupId = taskGroupId;


    // Enter missing link here?

    }
}

TaskFragment (receiving fragment):

public class TasksFragment extends ListFragment
        implements OnClickListener {
    private final static String TAG = "TaskItemFragment logging";

    private DoItDataSource dataSource;
    private List<Tasks> tasks;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_item, container, false);

        Button backButton = (Button) 
                view.findViewById(R.id.fragment_task_item_bar_back_button);

        dataSource = new DoItDataSource(getActivity());

        dataSource.open();
        tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
        dataSource.close();

        TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
        setListAdapter(adapter);

        backButton.setOnClickListener(this);

        return view;
    }

    public static TasksFragment newInstance() {
        TasksFragment tif = new TasksFragment();
        return tif;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.fragment_task_item_bar_back_button:
                ((MainActivity)getActivity()).setCurrentItem(0, true);
                break;
        }
    }
}

Solution

Thanks to Alireza! I had to make several changes to his proposed code, but in the end it helped me in finding the solution!

MainPageAdapter:

public class MainPagerAdapter extends FragmentStatePagerAdapter {
    // ADDED
    private String taskGroupId;

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

    @Override
    public Fragment getItem(int i) {
        switch (i) {
            case 0: return TaskGroupFragment.newInstance();
            // MODIFIED
            case 1:
                Bundle args = new Bundle();
                logcat("before setBundle " + taskGroupId);
                args.putString("taskGroupId",taskGroupId);
                Fragment fragment  =  new TasksFragment();
                fragment.setArguments(args);
                return fragment;
            default: return TaskGroupFragment.newInstance();
        }
    }

    // ADDED
    public void setTaskGroupId(String id){
        this.taskGroupId = id;
    }

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

MainActivity:

public class MainActivity extends FragmentActivity  implements
        TaskGroupFragment.OnTaskGroupSelectedListener{
    private SharedPreferences savedValues;

    private DoItDataSource dataSource = new DoItDataSource(this);

    private String identifier, user, domain;

    private JSONContainer containerToday;
    private JSONContainer containerTomorrow;

    // ADDED
    private MainPagerAdapter adapter;

    public ViewPager pager;

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

            savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
            identifier = savedValues.getString("Identifier", "");

            // ADDED
            adapter = new MainPagerAdapter(getSupportFragmentManager());

            pager = (ViewPager) findViewById(R.id.activity_main_pager);
            // MODIFIED
            pager.setAdapter(adapter);

            if (identifier == null || identifier.equals("")) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("APP_ID", APP_ID);
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        identifier = savedValues.getString("Identifier", "");
        user = savedValues.getString("User", "");
        domain = savedValues.getString("Domain", "");
        boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);

        //
        // Getting lists
        //
    }


    String taskGroupId = "";

    @Override
    public void onTaskGroupSelected(String taskGroupId) {
        this.taskGroupId = taskGroupId;

        // ADDED
        adapter.setTaskGroupId(taskGroupId);
        pager.setAdapter(adapter);
        pager.setCurrentItem(1);
    }
}

TaskFragment (receiving fragment):

public class TasksFragment extends ListFragment implements OnClickListener {
    private final static String TAG = "TaskItemFragment logging";

    private DoItDataSource dataSource;
    private List<Tasks> tasks;

    private String taskGroupId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_item, container, false);

        Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);

        dataSource = new DoItDataSource(getActivity());

        // ADDED
        Bundle bundle = getArguments();
        taskGroupId = bundle.getString("taskGroupId");

        // MODIFIED
        dataSource.open();
        tasks = dataSource.getTasks(taskGroupId);
        dataSource.close();

        TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
        setListAdapter(adapter);

        backButton.setOnClickListener(this);

        return view;
    }

    // CAN BE REMOVED?
    //public static TasksFragment newInstance() {
    //    TasksFragment tif = new TasksFragment();
    //    return tif;
    //}

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.fragment_task_item_bar_back_button:
                ((MainActivity)getActivity()).setCurrentItem(0, true);
                break;
        }
    }
}

Please note that I'm using taskGroupId as a String, not an int.

Was it helpful?

Solution

First you need to make sure your adapter knows about taskGroupID. just add a variable and a public method to your adapter.

public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;


public void setTaskGroupId(int id){
   this.taskGroupId = id;
}
}

then store a reference to your adapter in your activity. Now simply call this method whenever GroupId changes

    @Override
public void onTaskGroupSelected(String taskGroupId) {
    this.taskGroupId = taskGroupId;
    adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment. 
    adapter.setCurrentItem(1); //going to TasksFragment page

}

then you need to put some argumants before starting your fragment.

    @Override
    public Fragment getItem(int i) {
        //this code is only for case 1:
        Bundle args = new Bundle();
        args.putInt("taskGroupId",taskGroupId);
        Fragment fragment =  new TasksFragment();
        fragment.setArguments(args);
        return fragment;
    }

and lastly use this data in your TaskFragment to show the right content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top