0

OK, the relevant things:

I have a FragmentActivity (MainActivity.java) which holds the references to a one Fragment (Tab1Fagment.java), and two ListFragments (Tab2- & Tab3Fragment.java). The Tab3Activity is a ListFragment which is created dynamically upon some dates which are read from the SharedSettings. Now, the dates are being set in a Dialog which is being launched from the Tab3Fragment.

Well, my question is - how do I refresh the list in the Tab3Fragment when the dialog is dismissed? - the onCreateView method doesn't capture that event. The list is being refreshed if I switch to Tab1 and come back to Tab3 - but that's just a bad workaround.

The relevant codes:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;

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

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

    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
        actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar.addTab(actionBar.newTab()
                //.setText(mSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
        }
}

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

@Override
public void onTabSelected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.action_settings:
            DatePickerDialog datePickerDialog = new DatePickerDialog(this);
            datePickerDialog.show(); //moram ici ovako jer mi trebaju listeneri za share dugme
            getActionBar().selectTab(getActionBar().getTabAt(0));
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.

        switch (position) {
        case 0:
            // Tab1 fragment activity
            return new Tab1Fragment();
        case 1:
            // Tab2 fragment activity
            return new Tab2Fragment();
        case 2:
            // Tab3 fragment activity
            return new Tab3Fragment();
        }    
        return null;
    }

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

    //tab titles - not being used
    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}}

Tab3Fragment.java

public class Tab3Fragment extends ListFragment {

SharedPreferences settings;
ListView listView;
String [][] TAB3QUESTIONS_REARRANGED;
String TAB3TITLES[], TAB3SUBTITLES[], TAB3ANSWERS[];
Date dateTAB3DATES[];
long longDateTAB3DATES[]; //needed to pass as Bundle to DetailsFragment, because Date[] cannot be passed, must be converted to long
Date currentDate;
long currentDateInMilliseconds, savedBirthDate, savedJaydessDate, savedLastCheckDate;
Calendar calendarCurrentDate, calenderSavedBirthDate, calenderSavedJaydessDate, calenderSavedLastCheckDate;
TextView textView1, textView2;
boolean bigCheckup;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    //prepare file
    settings = getActivity().getSharedPreferences("jaydess_shared_pref", 0);

    //if dates were not found in the memory - display the date input dialog and a modified list
    if (!((settings.contains("savedBirthDate")) && (settings.contains("savedJaydessDate")))) {

        /*
        //if TAB3 is selected show date input dialog
        if (getActivity().getActionBar().getSelectedTab().getPosition() == 2) {
            //there were no saved dates found -> fire the dates activity
            DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity());
            datePickerDialog.show(); //moram ici ovako jer mi trebaju listeneri za share dugme
            //getActivity().getActionBar().selectTab(getActivity().getActionBar().getTabAt(0));
        }*/

        TAB3TITLES = new String[1];
        TAB3SUBTITLES = new String[1];
        dateTAB3DATES = new Date[1];
        longDateTAB3DATES = new long[1];
        TAB3TITLES[0] = DataStructure.TAB3EXCEPTIONMESSAGE[0];
        TAB3SUBTITLES[0] = DataStructure.TAB3EXCEPTIONMESSAGE[1];
    }
    else {
        //initialize the variables and read saved data
        initialize();       
        //run the titles, subtitles and answers arrangement procedure - THE TAB3 LOGIC
        rearrange();
    }    

    //load the arranged titles (main items)
    ArrayAdapter<String> adapter = new MyArrayAdapter<String>(getActivity(), TAB3TITLES);
    /** Setting the list adapter for the ListFragment */
    setListAdapter(adapter);

    return super.onCreateView(inflater, container, savedInstanceState);         
}


//needed for typeface setting in listFragments, see: http://stackoverflow.com/questions/14190648/change-font-of-list-fragment-on-detail-fragment
public class MyArrayAdapter<T> extends ArrayAdapter<T> {

    public MyArrayAdapter(Context context, List<T> items) {
        super(context, android.R.layout.simple_list_item_activated_2, android.R.id.text1, items);
    }

    public MyArrayAdapter(Context context, T[] items) {
        super(context, android.R.layout.simple_list_item_activated_2, android.R.id.text1, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = super.getView(position, convertView, parent);
        textView1 = (TextView) view.findViewById(android.R.id.text1);
        textView2 = (TextView) view.findViewById(android.R.id.text2);
        textView1.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/BryantPro-Medium.otf"));
        textView2.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/BryantPro-Light.otf"));

        //set the subtitles
        textView2.setText(TAB3SUBTITLES[position]);

        //if dates exist (if saved and read)
        if ((dateTAB3DATES[position] != null) && (currentDate != null)) {
            //set the color of passed items to GRAY
            if (dateTAB3DATES[position].before(currentDate)) {
                textView1.setTextColor(Color.GRAY);
                textView2.setTextColor(Color.GRAY);
            }
            else {
                textView1.setTextColor(Color.BLACK);
                textView2.setTextColor(Color.BLACK);
            }
        }
        return view;
    }      
} /////// ETC.....

DatePickerDialog.java

this class basically just saves the dates to sharedpreferences and dismisses the dialog

            saveData();
        dismiss();
Tautvydas
  • 2,027
  • 3
  • 25
  • 38

1 Answers1

0

You can repopulate the ListView on exiting the DatePickerDialog by calling adapter.clear() and adapter.addAll(). Alternatively, you could delete/add specific elements, however if the number of elements is low just repopulate as it will produce less bugs and you won't notice any difference.

To create a Dialog you can use this code inside the onCreate() of Tab3Fragment:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Message")
           .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   // take any needed action
                   Tab3Fragment.this.updateData();
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   // take any needed action
                   Tab3Fragment.this.updateData();
               }
           });
    Dialog dialog = builder.create();

You might want to add similar listener with setOnDismissListener which is called if user presses 'back'.

And in your Tab3Fragment define method that will be called from the Dialog:

private void updateData(){
    initialize();
    rearrange();
}

Now when you want to show the dialog just call dialog.show().

Tautvydas
  • 2,027
  • 3
  • 25
  • 38
  • I need to run the procedures initialize() and rearrange() (which are included in the onCreateView() of Tab3Fragment.class) prior to the adapter refresh. Now, given the above code examples, could you please give me a hint how to accomplish this from the Dialog, and how to instatiate my custom adapter? Thank you in advance. – user1570638 Feb 26 '14 at 11:15
  • Updated the main answer. – Tautvydas Feb 26 '14 at 17:02