How to show saved data inside multiple fragments? - android

Intro
Hi guys, currently I am working on a question-form app. In the MainActivity users can add an item after which a QuestionListActivity opens. Clicking on the first item in that list opens the Main2Activity. This activity exists of 3 fragments which all include one question (Edittext). The data implemented by the user in the fragments is saveable. After answering and saving questions, each form appears in the MainActivity as a list. Clicking on these items brings them back to the QuestionListActivity after which clicking on the first item should open the fragments again with their saved data already shown.
Problem
After saving the fragments, the string to the MainActivity is succesfull, eg. the Title as set by saving the first fragment (which asks for the name of the form). Therefore, the saving to my Utilities class was succesfull. The problem is, clicking on a saved item in the MainActivity and then on the first item in the QuestionList to open the Main2Activity (fragments with questions), opens the fragments but with empty EditText fields where the saved data should be shown to view them or make changes.
Question
How is it possible to show the saved data inside multiple fragments instead of in just one activity and what am I doing wrong? And is it recommended to use the same format when using 8 questions (one fragment per question)?
(I couldn't find the right question to use on StackOverFlow, because almost every question about this subject is about the instance state ed. but this isn't a problem in my project)
Codes
Here is my Main2Activity and one fragment(Frag1). The other fragment I have setup the same way as Frag1. I am probably doing something wrong in the fragment java classes but I am unsure what. Hopefully, someone can help me.
public class Main2Activity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private String mNoteFileName;
private Note mLoadedNote;
private EditText title, question2, question3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title = findViewById(R.id.note_et_title1);
question2 = findViewById(R.id.note_et_question2);
question3 = findViewById(R.id.note_et_question3);
String title;
String question2 ;
String question3;
mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
if(mNoteFileName !=null && !mNoteFileName.isEmpty()) {
mLoadedNote = Utilities.getNoteByName(this, mNoteFileName);
if(mLoadedNote !=null) {
title = mLoadedNote.getTitle();
question2 = mLoadedNote.getQuestion2();
question3 = mLoadedNote.getQuestion3();
}
}
List<Fragment> fragments = new ArrayList<>();
fragments.add(Frag1.newInstance(title));
fragments.add(Frag2.newInstance(question2));
fragments.add(Frag3.newInstance(question3));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),fragments);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_note_new, menu);
return true;
}
private void saveNote() {
Note note;
if(title.getText().toString().trim().isEmpty()){
Toast.makeText(this, "Please enter a title", Toast.LENGTH_SHORT).show();
}
if(mLoadedNote ==null) {
note = new Note(System.currentTimeMillis(), title.getText().toString(), question2.getText().toString(), question3.getText().toString());
}else {
note = new Note(mLoadedNote.getDateTime(), title.getText().toString(), question2.getText().toString(), question3.getText().toString());
}
if (Utilities.saveNote(this, note)){
Toast.makeText(this, "saved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "not enough space", Toast.LENGTH_SHORT).show();
}
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_note_save:
saveNote();
break;
}
return true;
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
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) {
View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
mFragments = fragments;
}
#Override
public Fragment getItem(final int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
}
}
public class Frag1 extends Fragment {
private static final String EXTRA_TEXT = "text";
private EditText mEtTitle;
public static Frag1 newInstance(String message) {
Bundle args = new Bundle();
args.putString(EXTRA_TEXT, message);
Frag1 fragment = new Frag1();
fragment.setArguments(args);
return fragment;
}
public Frag1 () {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag1_layout, container, false);
mEtTitle = (EditText) view.findViewById(R.id.note_et_title1);
Bundle bundle = getArguments();
if (bundle != null) {
mEtTitle.setText(bundle.getString(EXTRA_TEXT));
}
return view;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_green_light">
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="Vraag 1, bv naam" />
<EditText
android:id="#+id/note_et_title1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:gravity="top"
android:inputType="textMultiLine" />

I would recommend you to slighlty change your current approach.
First create helper method newInstance in each fragment which will return the instance of that fragment. For example Frag1
public class Frag1 extends Fragment {
private static final String EXTRA_TEXT = "text";
private EditText mEtTitle;
public static Frag1 newInstance(String message) {
Bundle args = new Bundle();
args.putString(EXTRA_TEXT, message);
Frag1 fragment = new Frag1();
fragment.setArguments(args);
return fragment;
}
public Frag1 () {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag1_layout, container, false);
mEtTitle = (EditText) view.findViewById(R.id.note_et_title1);
Bundle bundle = getArguments();
if (bundle != null) {
mEtTitle.setText(bundle.getString(EXTRA_TEXT));
}
return view;
}
}
In SectionsPagerAdapter pass the list of Fragment.
For the reference hereby modified SectionsPagerAdapter.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
mFragments = fragments;
}
#Override
public Fragment getItem(final int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
}
Then change the call
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),<List of Fragments>);
Hereby sharing modified Activity#onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String title = "";
String question2 = "";
String question3 = "";
mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
if(mNoteFileName !=null && !mNoteFileName.isEmpty()) {
mLoadedNote = Utilities.getNoteByName(this, mNoteFileName);
if(mLoadedNote !=null) {
title = mLoadedNote.getTitle();
question2 = mLoadedNote.getQuestion2();
question3 = mLoadedNote.getQuestion3();
}
}
List<Fragment> fragments = new ArrayList<>();
fragments.add(Frag1.newInstance(title));
fragments.add(Frag2.newInstance(question2));
fragments.add(Frag3.newInstance(question3));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),fragments);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}

You should use Shared Preferences or Database to save your data and show it.

Related

Changing tabs of TabLayout programmatically but fragments of ViewPager is not updated

I am developing an Android app. In my app, I am using TabLayout with ViewPager. I need to update the Tabs of TabLayout and its fragments programmatically when an item at the bottom navigation bar is selected. I can update the tabs of TabLayout. But the fragments of pager are not updated.
This is the issue:
As you can see in the above, tabs are changed but its fragments are not changed. List Fragment is always displayed. All the fragments are just the same with the first tab selected. I mean fragments are not changing at all.
This is my XML file for the tabs and view pager:
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/ma_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/ma_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
This is my whole activity:
public class MainActivity extends AppCompatActivity {
private BottomBar bottomBar;
private TabLayout topTabLayout;
private ViewPager mainViewPager;
private MainPagerAdapter pagerAdapter;
private ArrayList<Fragment> pagerFragments;
private ArrayList<String> pagerTitleList;
protected TfrApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (TfrApplication)getApplication();
setContentView(R.layout.activity_main);
initialize();
initViews();
setUpViews();
}
private void initialize()
{
pagerFragments = new ArrayList<Fragment>();
pagerTitleList = new ArrayList<String>();
}
private void initViews()
{
bottomBar = (BottomBar)findViewById(R.id.ma_bottom_action_bar);
mainViewPager = (ViewPager)findViewById(R.id.ma_viewpager);
topTabLayout = (TabLayout)findViewById(R.id.ma_tab_layout);
}
private void setUpViews()
{
pagerAdapter = new MainPagerAdapter(getSupportFragmentManager(),pagerFragments,pagerTitleList);
mainViewPager.setAdapter(pagerAdapter);
topTabLayout.setupWithViewPager(mainViewPager);
setUpBottomBar();
}
private void clearPagerFragments()
{
if(pagerAdapter!=null && pagerFragments!=null && pagerFragments.size()>0)
{
pagerFragments.removeAll(pagerFragments);
pagerTitleList.removeAll(pagerTitleList);
pagerAdapter.notifyDataSetChanged();
}
}
private void setUpNewsPagerFragments()
{
NewsFragment latestNewsFragment = new NewsFragment();
Bundle latestNewsBundle = new Bundle();
latestNewsBundle.putInt(NewsFragment.FIELD_CATEGORY_ID,0);
latestNewsBundle.putInt(NewsFragment.FIELD_LEAGUE_ID,0);
latestNewsBundle.putInt(NewsFragment.FIELD_COUNTRY_ID,0);
latestNewsBundle.putInt(NewsFragment.FIELD_TEAM_ID,0);
latestNewsFragment.setArguments(latestNewsBundle);
pagerTitleList.add("LATEST");
pagerFragments.add(latestNewsFragment);
PrioritizedTeamsFragment teamsFragment = new PrioritizedTeamsFragment();
pagerTitleList.add("TEAMS");
pagerFragments.add(teamsFragment);
NewsFragment articlesFragment = new NewsFragment();
Bundle articlesBundle = new Bundle();
articlesBundle.putInt(NewsFragment.FIELD_CATEGORY_ID, 0);
articlesBundle.putInt(NewsFragment.FIELD_LEAGUE_ID, 0);
articlesBundle.putInt(NewsFragment.FIELD_COUNTRY_ID, 0);
articlesBundle.putInt(NewsFragment.FIELD_TEAM_ID, 0);
articlesFragment.setArguments(articlesBundle);
pagerTitleList.add("ARTICLES");
pagerFragments.add(articlesFragment);
TopFragment topFragment = new TopFragment();
pagerTitleList.add("TOP 10");
pagerFragments.add(topFragment);
}
private void setUpMatchesPagerFragments()
{
MatchesFragment matchesFragment = new MatchesFragment();
pagerTitleList.add("MATCHES");
pagerFragments.add(matchesFragment);
StatisticsFragment statisticsFragment = new StatisticsFragment();
pagerTitleList.add("STATISTICS");
pagerFragments.add(statisticsFragment);
}
private void setUpBottomBar()
{
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(int tabId) {
switch (tabId){
case R.id.bottom_tab_news:
clearPagerFragments();
setUpNewsPagerFragments();
pagerAdapter.notifyDataSetChanged();
break;
case R.id.bottom_tab_matches:
clearPagerFragments();
setUpMatchesPagerFragments();
pagerAdapter.notifyDataSetChanged();
topTabLayout.getTabAt(0).select();
break;
case R.id.bottom_tab_meme:
Toast.makeText(getBaseContext(),"MEME",Toast.LENGTH_SHORT).show();
break;
case R.id.bottom_tab_settings:
Toast.makeText(getBaseContext(),"Settings",Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}
I showed the whole activity because code the whole activity dealing with that problem. Besides, the whole activity only contains code for creating tabs, view pager and bottom bar. All are connected.
This is my view pager adapter:
public class MainPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList;
private ArrayList<String> titleList;
public MainPagerAdapter(FragmentManager fragmentManager,ArrayList<Fragment> fragmentsParam,ArrayList<String> titlesParam)
{
super(fragmentManager);
this.fragmentList = fragmentsParam;
this.titleList = titlesParam;
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
Why is the content or fragments of view pager are not changed when tabs are changed? What is wrong with my code?
As you can see on bottom item selected listener I tried to set the selected fragment like this:
topTabLayout.getTabAt(0).select();
I tried this as well:
mainViewPager.setCurrentItem(0);
Both are not working.
try to add a method to swap the fragment-list and call notifyDataSetChanged() in your adapter like this:
public void notifyDataSetChanged(List<Fragment> list) {
fragmentList.removeAll();
fragmentList.addAll(list);
notifyDataSetChanged();
}
changing data in activity and call adapter.notifyDataSetChanged() may fail to update your view.You can log in getItem() to check if the adapter knows the data set has changed.
Just Check which layout you are inflating in MatchesFragment class.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.matches_fragment, container, false);
}
If your tab is set correctly, under the code where the tab is set, run this again:
mainViewPager.setAdapter(pagerAdapter);
Here is my code:
selectedTab = 0;
tabLayout.getTabAt(selectedTab).select();
viewPager.setAdapter(tabsAdapter);

Android Weird Error : Fragement Dosen't Recreats The View

HERE IS THE VIDEO:
https://www.youtube.com/watch?v=eush2bY0XlQ&feature=youtu.be&hd=1
So here is the plot :
1) I have a navigation drawer.
2) By Clicking on one of the list item a tab layout (fragment) is inflated .
3) So I get a tab layout (with 6 tabs) working besides navigation drawer i.e navigation drawer and tab_layout can be used simultaneously.
4) Content of every tab is a Different fragement.
Problem :
When I launch the application and click the list-item with the tab fragment the content of the tab_fragment is inflated normally.
But when i click it again all the content of the first and second tab dissappear.
And reappear only when when i swipe till the third tab and swipe back again .
In simple words ,
On Calling the static new Instance method of Tab_Fragment for the first time is works fine .
On Calling it again the content of the first and second tab disappear and reappear
only when I swipe till the 3rd tab and come back.
I know it sounds weird.
Code:
My Tab_Fragment To Create it I call its New Instance From MainActivity.
public class Tab_Activity extends Fragment {
private final Handler handler = new Handler();
public PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
public final static String TAG = Tab_Activity.class.getSimpleName();
public Tab_Activity() {
// TODO Auto-generated constructor stub
}
public static Tab_Activity newInstance() {
return new Tab_Activity();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_layout, container, false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(v, savedInstanceState);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
pager = (ViewPager) v.findViewById(R.id.pager);
adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
tabs.setIndicatorColorResource(R.color.grey);
tabs.setTextColorResource(R.color.black);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { " ELECTRONICS ", " IT ", " COMPUTER "," EXTC ", "INSTRUMENTATION"," MCA " };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return Courses.newInstance(position);
}
}
}
The Courses Fragment :
public class Courses extends Fragment {
LinearLayout ll ;
private static final String ARG_POSITION = "position";
public static PagerSlidingTabStrip tab ;
private int position;
public static Courses newInstance(int position) {
Courses f = new Courses();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dept_main,container,false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(v, savedInstanceState);
// generate ID's :
TextView h_name = (TextView) v.findViewById(R.id.tv_dept_name);
TextView f_info = (TextView) v.findViewById(R.id.tv_dept_info);
TextView h_vision = (TextView) v.findViewById(R.id.header_vision);
TextView f_vision = (TextView) v.findViewById(R.id.footer_vision);
TextView h_mission = (TextView) v.findViewById(R.id.header_mission);
TextView f_mission = (TextView) v.findViewById(R.id.footer_mission);
TextView h_eoe = (TextView) v.findViewById(R.id.header_EOE);
TextView f_eoe = (TextView) v.findViewById(R.id.footer_EOE);
TextView h_intake = (TextView) v.findViewById(R.id.header_intake);
TextView f_intake = (TextView) v.findViewById(R.id.footer_intake);
h_intake.setText(R.string.h_intake);
h_mission.setText(R.string.h_mission);
h_vision.setText(R.string.h_vision);
h_eoe.setText(R.string.h_eoe);
switch(position){
case 0 :
//Electronics
h_name.setText("Electronics");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_etrx);
f_mission.setText(R.string.m_etrx);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_etrx);
break ;
case 1 :
h_name.setText("Information Technology");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_it);
f_mission.setText(R.string.m_it);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_it);
break ;
case 2 :
h_name.setText("Computer Science");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_coms);
f_mission.setText(R.string.m_coms);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_coms);
break ;
case 3 :
h_name.setText("Electronics And Telecommunication");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_extc);
f_mission.setText(R.string.m_extc);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_extc);
break ;
case 4 :
h_name.setText("Instrumentation");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_it);
f_mission.setText(R.string.m_it);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_it);
break ;
case 5 :
h_name.setText("Master of Computer Applications");
f_info.setText("Post Graduation Course.(PG)");
f_vision.setText(R.string.v_mca);
f_mission.setText(R.string.m_mca);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_mca);
break;
}
}
}
(Comment for any clarifications ! )
Found My Answer ==> https://stackoverflow.com/a/12582529/3475933
Only Changed FragmenPagerAdapter to FragmentStatePagerAdapter and eveything worked fine.
Hope it helps .!

Refresh Fragment Views based on Button Click

I have 2 fragments (tabs) that share some data. When one changes the data, I'd like to have that reflected on the other tab. I researched this on stackOverflow and I think the relevant answer has to do with a .notifyDataSetChanged() call, but I can't make it work. Here's the relevant code...
public class EnterCourseData extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Pars", "Handicaps" };
private int courseNumber, teeNumber;
private Tee tee;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_tees);
// Initilization
Intent mIntent = getIntent();
courseNumber = mIntent.getIntExtra("courseNumber",0);
Course course = Global.getCourse(courseNumber);
teeNumber = mIntent.getIntExtra("teeNumber",0);
tee = course.getTee(teeNumber);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), courseNumber, teeNumber);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
and further down, here is the onClick method that necessitates the refresh...
public void savePars(View view){
tee.setSlope(Integer.parseInt(((EditText) findViewById(R.id.enter_tee_slope)).getText().toString()));
tee.setRating(Double.parseDouble(((EditText) findViewById(R.id.enter_tee_rating)).getText().toString()));
mAdapter.notifyDataSetChanged();
}
Here is the TabsPagerAdapter...
public class TabsPagerAdapter extends FragmentPagerAdapter {
int courseNumber, teeNumber;
public TabsPagerAdapter(FragmentManager fm, int courseNumber, int teeNumber) {
super(fm);
this.courseNumber = courseNumber;
this.teeNumber = teeNumber;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Par Entry activity
Fragment parFragment = new ParFragment();
Bundle args = new Bundle();
args.putInt(ParFragment.ARG_COURSE_NUMBER, courseNumber);
args.putInt(ParFragment.ARG_TEE_NUMBER, teeNumber);
parFragment.setArguments(args);
return parFragment;
case 1:
// Handicap Entry fragment activity
Fragment hcpFragment = new HandicapFragment();
args = new Bundle();
args.putInt(HandicapFragment.ARG_COURSE_NUMBER, courseNumber);
args.putInt(HandicapFragment.ARG_TEE_NUMBER, teeNumber);
hcpFragment.setArguments(args);
return hcpFragment;
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
Here is one Fragment...
public class ParFragment extends Fragment {
public static final String ARG_COURSE_NUMBER = "courseNumber", ARG_TEE_NUMBER = "teeNumber";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_par, container, false);
Bundle args = getArguments();
Course course = Global.getCourse(args.getInt(ARG_COURSE_NUMBER));
((TextView) rootView.findViewById(R.id.display_course_name)).setText(course.getName());
Tee tee = course.getTee(args.getInt(ARG_TEE_NUMBER));
((TextView) rootView.findViewById(R.id.display_tee_name)).setText(tee.getTeeName());
((TextView) rootView.findViewById(R.id.enter_tee_slope)).setText(Integer.toString(tee.getSlope()));
((TextView) rootView.findViewById(R.id.enter_tee_rating)).setText(Double.toString(tee.getRating()));
return rootView;
}
}
And here is the other...
public class HandicapFragment extends Fragment {
public static final String ARG_COURSE_NUMBER = "courseNumber", ARG_TEE_NUMBER = "teeNumber";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_handicap, container, false);
Bundle args = getArguments();
Course course = Global.getCourse(args.getInt(ARG_COURSE_NUMBER));
((TextView) rootView.findViewById(R.id.display_course_name)).setText(course.getName());
Tee tee = course.getTee(args.getInt(ARG_TEE_NUMBER));
((TextView) rootView.findViewById(R.id.display_tee_name)).setText(tee.getTeeName());
((TextView) rootView.findViewById(R.id.enter_tee_slope)).setText(Integer.toString(tee.getSlope()));
((TextView) rootView.findViewById(R.id.enter_tee_rating)).setText(Double.toString(tee.getRating()));
return rootView;
}
}
When the button is clicked, I want to save the values and I want these values to show up on the other fragment.
Help a noob out.
Thanks
You need to communicate between fragments, but a fragment cannot directly communicate with other fragment, all the communication should be done through the activity which holds these fragments.
The steps to follow are :
Define an Interface in the fragment where you have implemented the onClickListener (let it be Fragment A)
Implement the Interface in the activity which holds these fragments
In the method overridden, retrieve the fragment instance from the viewpager adapter and deliver a message to Fragment B by calling it's public methods.
refer this answer to retrieve fragment instance from adapter
For more details about Communicating with Other Fragments, refer here
So there is a trick: just let the fragments have the object reference of one another and call the other's function to load data when you handle the onClickListener of the button.
E.g:
protected void onClickListener(View view) {
if (view == myButton) {
// Do other stuffs here
fragment1.reloadData();
}
}
P/S : I re-post this as answer to have the code formatter.

Android Display and save data in next tab

I have created a FragmentActivity of 2 tabs. This is a very basic Tab example from Android Developer tutorial using FragmentActivity and FragmentPagerAdapter Code Here
public class FragmentPagerSupport extends FragmentActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
static final int NUM_ITEMS = 10;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
...........
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (position) {
case 0:
fragment = new Fragment01();
args.putInt(Fragment01.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
break;
case 1:
fragment = new Fragment02();
args.putInt(Fragment02.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
break;
return fragment;
}
}
Then I have created 2 different fragments for 2 tabs:
public static class Fragment01 extends Fragment {
private EditText mName;
private EditText mEmail1;
public static final String ARG_SECTION_NUMBER = "2";
public Fragment01() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_customer_add, container, false);
mName = (EditText) v.findViewById(R.id.customer_add_name);
mEmail = (EditText) v.findViewById(R.id.customer_add_email);
View confirmButton = v.findViewById(R.id.customer_add_button);
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
......................
}
});
}
}
Now in the 2nd tab I need to show the input value of Name and Email from 1st tab and on confirm from 2nd tab need to save in database. But here I stuck. I am not getting an idea how I can keep data from first tab? Please help.
One approach could be to use Singleton DP. There will be only one object having Name, Email etc. as fields. Set Name and Email fields using setters when you are in first fragment and access them using getters in second fragment.
On confirm, you can insert entire object into database.

onClick inside fragment giving me NPE

I've been wrestling with this for quite a while now.
I switched from having a regular Activity to now using fragments (by users recommendations), but I've been getting the same issue.
I have 3 pages that are now 3 fragments inside of a ViewPager. I want the button with the id addSiteButton in the addSite fragment; when clicked, to scroll over to setCurrentItem(2).
Any help is appreciated! Here's my code.
The FragmentActivity
public class fieldsActivity extends FragmentActivity {
private static final int NUMBER_OF_PAGES = 3;
ViewPager mPager;
MyFragmentPagerAdapter mMyFragmentPagerAdapter;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
mPager = (ViewPager) findViewById(R.id.fieldspager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyFragmentPagerAdapter);
mPager.setCurrentItem(1);
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int page) {
switch (page) {
case 0: return new settingFields();
case 1: return new addSite();
case 2: return new createSite();
}
return null;
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
The class with the button
public class addSite extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (container == null) {
return null;
}
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.add_site, container, false);
final ViewPager mPager = (ViewPager) mRelativeLayout.findViewById(R.id.fieldspager);
Button addSiteButton = (Button) mRelativeLayout.findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
});
return mRelativeLayout;
}
}
I feel like I'm going in circles and not getting the desired motion.
Thanks for the help!
Simply make the Fragment as a class inside the FragmentActivity and take out the variable shadowing in onCreateView() since your pager is a global variable.
public class fieldsActivity extends FragmentActivity {
private static final int NUMBER_OF_PAGES = 3;
ViewPager mPager;
MyFragmentPagerAdapter mMyFragmentPagerAdapter;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
mPager = (ViewPager) findViewById(R.id.fieldspager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyFragmentPagerAdapter);
mPager.setCurrentItem(1);
}
public static class addSite extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.add_site, container, false);
//final ViewPager mPager = (ViewPager) mRelativeLayout.findViewById(R.id.fieldspager);
Button addSiteButton = (Button) mRelativeLayout.findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
});
return mRelativeLayout;
}
}
}
Also consider using the #Override annotation whenever you override a method so you don't make mistakes and use proper naming conventions. Java classes start with a capital.

Categories

Resources