Android support ViewPager holds reference to old fragments

I was implementing a feature where I have a service that retrieves data on background and an activity receives results and updates one of the fragments with new data.

Everything went well until I rotated the screen and the application was re-created and fragments and fragments pager was initialized again. After that new data did not show up. At that point I was totally uncertain what was wrong. At first I was thinking the problem was with the service, but it turned out that nothing was wrong there. After struggling a while I noticed that the fragment that was  re-created was not attached to the view at all.

That led me to this Stack Overflow question and one answer provided a solution for me as well. The problem lies on Compatibility library v.4 ViewPager (bug report) combined with FragmentPagerAdapter. In some level ViewPager or FragmentPagerAdapter holds references to old fragments and does not refresh them correctly.

One working solution is to use FragmentStatePagerAdapter instead of FragmentPagerAdapter. However I resolved my issue with the help of this answer.

I implemented getFragmentTag() method in my FragmentPagerAdapter class

private String getFragmentTag(int pos){
    return "android:switcher:"+R.id.viewpager+":"+pos;
}

change R.id.viewpager to match with you ViewPager compnent’s id.

Then in my Activity I find reference to the Fragment like this.

...
this.mPagerAdapter  = new MyPagerAdapter(getSupportFragmentManager(), fragments, titles);
this.pager = (ViewPager)super.findViewById(R.id.viewpager);
this.pager.setAdapter(this.mPagerAdapter);
int position = 3;
this.myFragment = (MyFragment)getSupportFragmentManager().findFragmentByTag(mPagerAdapter.getFragmentTag(position));
...

And after service returned new data I simply call

...
myFragment.updateData(data);
...

Hopefully this saves someones time to figure out what is wrong instead of hours of investigation.

Advertisements

ExpandableListView with CheckedTextView

ExpandableListView

I was implementing a settings list activity with CheckedTextView and I found out that Android’s ExpandableListView is a handy component to display some hierarchical data. However in my case there was one weakness. You can not see which items are selected when a parent group is collapsed. I wanted to display the text of selected child items in the parent view. My biggest problem was that I couldn’t reach the parent view in reliably way when child item was clicked.

I tried to search from the internets are there any solutions ready, but I found nothing there (or I used wrong search terms). As earlier I made my own solution.

My ExpandableListView solution is based on this tutorial. 

I solved parent view issue by setting unique tag to parent view in Adapter class.

@Override
//in this method you must set the text to see the parent/group on the list
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {

if (view == null) {
view = inflater.inflate(R.layout.settings_list_item_parent, viewGroup,false);
}
// set category name as tag so view can be found view later
view.setTag(getGroup(i).toString());

….

}

Based on that tag I can find parent view later when child item is clicked.

@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {

CheckedTextView checkbox = (CheckedTextView)v.findViewById(R.id.list_item_text_child);
checkbox.toggle();

// find parent view by tag
View parentView = categoriesList.findViewWithTag(categories.get(groupPosition).name);


}

One nice feature that I have used in my ExpandableListView is autocollapse feature that I found here.

Get the full source code here: https://github.com/nevalla/expandablelistview-demo

Android libraries I have used recently

Liigavahti Android app
Liigavahti Android app

I have implemented an Android application called Liigavahti. It is only in Finnish, but basic idea is to provide Finnish ice hockey news streams to users. Application includes Twitter stream as well.

When implementing the application I found out couple of great libraries that helped me a lot and I would like to share them to you:

ActionBarSherlock [http://actionbarsherlock.com/]

ActionBarSherlock is an extension of the support library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API.

Basically it provides same functionality than native ActionBar to older Android versions.

ViewPageIndicator [http://viewpagerindicator.com/]

ViewPageIndicator provides paging indicator widgets compatible with the ViewPager from the Android Support Library and ActionBarSherlock. Also here this library brings functinality of ViewPager to older Android versions

Android-PullToRefresh [https://github.com/chrisbanes/Android-PullToRefresh]

Android-PullToRefrehs project aims to provide a reusable Pull to Refresh widget for Android. You have seen this kind of functionality in several mobile apps like Twitter and Facebook. This library makes it easy to implement that kind of functionality.

GitHub Android App [https://github.com/github/android]

Actually this is not a library, but why I mention this is the reason that it helped me a lot to understand how to do things right way. So if you have some spare time I suggest you to check this out. Be careful you might learn something

When I was implementing my application I struggled a while with examples I found. So I will provide some simple tutorials how to use these libraries. So stay tuned!

How to implement CalendarView in Android

Android does not offer any calendar view in the SDK. That is a big loss from the developer’s point of view. There are lots of situations where it would be beneficial to display days of a month and provide some option for the user to choose the day.

One solution is to use a 3rd party component. The second one is to implement one by your own, like I did.

Picture 1. CalendarView

When I started to implement  the calendar view, I googled around with some search terms and found this tip.

AFAIK, there are no other way than implement your own calendar. So… what you would have to do is using a GridLayout with 7 columns and create a custom BaseAdapter to display data correctly.

That sounded reasonable and I went ahead and tried it. My aim was to implement a single calendar view where user can navigate between months and choose a date (Picture 1). You can see the result here: https://github.com/nevalla/CalendarView

Basically two classes are needed to create the implementation mentioned above. One class to display calendar grid and the other one to adapt calendar days and items into the grid.

CalendarView.java

CalendarView is  a class that encapsulates the UI of the Calendar:  a header (navigation and name of the month) and a GridView.  onCreate() method does some initializations and res/layout/calendar.xml is set for the content view. Then handler attribute is used to populate some calendar items into to the calendar. Finally some event listeners are set. GridView’s OnClickListener returns selected date as string format:

gridview.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    	TextView date = (TextView)v.findViewById(R.id.date);
        if(date instanceof TextView && !date.getText().equals("")) {

        	Intent intent = new Intent();
        	String day = date.getText().toString();
        	if(day.length()==1) {
        		day = "0"+day;
        	}
        	// return selected date as string format
        	intent.putExtra("date", android.text.format.DateFormat.format("yyyy-MM", month)+"-"+day);
        	setResult(RESULT_OK, intent);
        	finish();
        }

    }
});

refreshCalendar() method asks calendar adapter to refresh itself and changes month name.
onNewItem() method captures date parameter and sets it as current date.

CalendarAdapter.java

CalendarAdapter is a class that handles the content of the calendar – how many days to display and whether to display calendar item icon or not.

refreshDays() method formats source array for the grid. Application assumes that weeks start on Monday, thus calculation is needed on how many empty days are before the first day of the month.

getView() method creates a view for each item referenced by the adapter. Layout of the view is defined in res/layout/calendar_item.xml.

CalendarViewSampleActivity.java

CalendarViewSampleActivity is an activity class that opens CalendarView. DatePicker’s date is updated by the return  value of the CalendarView.
So this is relatively simplified example of how to display calendar month and populate some items into it. How do you like it and how would you improve it?

UPDATE 1:

Since API level 11 (Android 3.0) there has been the native implementation of the CalendarView. However it’s just the view where you can pick a date, no calendar items can be shown.