1

I have a variable in MainActivity that I have successfully passed to StoriesActivity.

The problem is with getting it from there to StoriesFragment, which is a TabLayout tab.

I understand about Intents and Bundles but I'm not sure how they'd work in this instance.

This is StoriesActivity:

public class StoriesActivity extends AppCompatActivity {

    //This is our tablayout
    private TabLayout tabLayout;

    //This is our viewPager
    private ViewPager viewPager;

    private Toolbar toolbar;

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

        /* +++ START Intent +++ */
        Bundle extras = getIntent().getExtras();

        final int authorID = extras.getInt("author_id");
        final String authorName = extras.getString("author_name");
        Log.i("click", Integer.toString(authorID));
        // this is successful
        /* +++ END Intent +++ */

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(authorName);
        setSupportActionBar(toolbar);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new StoriesFragment(), "Stories");
        adapter.addFragment(new CollectionsFragment(), "Collections");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

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

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

And this is StoriesFragment (which doesn't work at the moment because it's not accessing the authorID variable from StoriesActivity):

public class StoriesFragment extends Fragment {

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

    private ListView storiesListView;

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

        // link ListView object with XML ListView
        storiesListView = (ListView) findViewById(R.id.stories_list_view);

        // create new instance of DatabaseHelper
        DatabaseHelper db = new DatabaseHelper(this);

        // create list of stories through getAllStories method
        List<Book> storyList = db.getAllStories(authorID);

        // create new ArrayAdapter
        ArrayAdapter<Book> arrayAdapter =
                new ArrayAdapter<Book>(this, android.R.layout.simple_list_item_1, storyList);

        // link ListView and ArrayAdapter
        storiesListView.setAdapter(arrayAdapter);

        Log.i("test", storyList.toString());

        storiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Book story = (Book) storiesListView.getItemAtPosition(i);
                //Log.i("click", story);

                Intent intent = new Intent(StoriesActivity.this, StoryBodyActivity.class);
                intent.putExtra("story", story.getTitle());
                startActivity(intent);

                //Log.i("click", "That's a click!");
            }
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_stories, container, false);
    }

}

StoriesTabsAdapter:

public class StoriesTabsAdapter extends FragmentPagerAdapter {

    int mNumOfTabs;


    public StoriesTabsAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    private String[] tabTitles = new String[]{"Stories", "Collections"};

    // overriding getPageTitle()
    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                StoriesFragment tab1 = new StoriesFragment();
                return tab1;
            case 1:
                CollectionsFragment tab2 = new CollectionsFragment();
                return tab2;
            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return tabTitles.length;
    }

}
Sebastian
  • 3,548
  • 18
  • 60
  • 95
  • this will help you https://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android – Pavan Nov 04 '17 at 17:49
  • Thanks @Pavan. What I'm not sure about is where the first block of code would go in my StoriesActivity. – Sebastian Nov 04 '17 at 17:52
  • are you asking how to send Bundle data in your stories fragment? – Pavan Nov 04 '17 at 17:55
  • Yes - I'm trying to pass on the bundle that was brought into StoriesActivity from MainActivity (in the lines after `/* +++ START INTENT +++ */`) but I'm not sure where to pass them to `StoriesFragment()` and `CollectionsFragment()`. – Sebastian Nov 04 '17 at 17:58

2 Answers2

0

for sending bundle data from your StoriesActivity

 private void setupViewPager(ViewPager viewPager) {
     Bundle bundle = new Bundle();
     bundle.putString("your_key", "yourdata");
    // set Fragmentclass Arguments
    StoriesFragment fragStory = new StoriesFragment();
    fragStory.setArguments(bundle);
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(fragStory, "Stories");
    adapter.addFragment(new CollectionsFragment(), "Collections");
    viewPager.setAdapter(adapter);
}
Pavan
  • 5,016
  • 1
  • 26
  • 30
  • Thank you. The issue is that `final int authorID` which I want to pass sits in my `onCreate`. How can I access it? – Sebastian Nov 04 '17 at 18:03
  • declare authorID as class level property not local – Pavan Nov 04 '17 at 18:04
  • Thanks. How would I then get the arguments in the Fragment? `Bundle bundle = getArguments();` returns null – Sebastian Nov 04 '17 at 19:24
  • As I think because you creating fragment in adapter class without bundle argument apply same logic there as example shown – Pavan Nov 04 '17 at 19:28
0

Here is solution to your problem:

This is your activity:

public class StoriesActivity extends AppCompatActivity {

    //This is our tablayout
    private TabLayout tabLayout;

    //This is our viewPager
    private ViewPager viewPager;

    private Toolbar toolbar;

    private int authorID;
    private String authorName;

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

        /* +++ START Intent +++ */
        Bundle extras = getIntent().getExtras();

        authorID = extras.getInt("author_id");
        authorName = extras.getString("author_name");
        Log.i("click", Integer.toString(authorID));
        // this is successful
        /* +++ END Intent +++ */

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(authorName);
        setSupportActionBar(toolbar);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(StoriesFragment.newInstance(authorID, authorName), "Stories");
        adapter.addFragment(new CollectionsFragment(), "Collections");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

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

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

This is your fragment:

public class StoriesFragment extends Fragment {

    private int authorID;
    private String authorName;

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

    public static StoriesFragment newInstance(int authorID, String authorName) {

        Bundle args = new Bundle();
        args.putInt("author_id", authorID);
        args.putString("author_name", authorName);

        StoriesFragment fragment = new StoriesFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private ListView storiesListView;

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

        // Here is your arguments
        authorID = getArguments().getInt("author_id");
        authorName = getArguments().getString("author_name");

        // link ListView object with XML ListView
        storiesListView = (ListView) findViewById(R.id.stories_list_view);

        // create new instance of DatabaseHelper
        DatabaseHelper db = new DatabaseHelper(this);

        // create list of stories through getAllStories method
        List<Book> storyList = db.getAllStories(authorID);

        // create new ArrayAdapter
        ArrayAdapter<Book> arrayAdapter =
                new ArrayAdapter<Book>(this, android.R.layout.simple_list_item_1, storyList);

        // link ListView and ArrayAdapter
        storiesListView.setAdapter(arrayAdapter);

        Log.i("test", storyList.toString());

        storiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Book story = (Book) storiesListView.getItemAtPosition(i);
                //Log.i("click", story);

                Intent intent = new Intent(StoriesActivity.this, StoryBodyActivity.class);
                intent.putExtra("story", story.getTitle());
                startActivity(intent);

                //Log.i("click", "That's a click!");
            }
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_stories, container, false);
    }

}

Hope it will help you.

Ibrokhim Kholmatov
  • 1,079
  • 2
  • 13
  • 16