I was experimenting on Android fragments, hence I created two fragments ListFragment and DetailFragment. The problem is that when I click on the ListFragment and call a DetailFragment method to show the selected item from the ListFragment no result is shown on the DetailFragment. Here is the DetailFragment Code :
private static final String DETAIL_FRAG_TAG = "detail_fragment";
private Context appContext = null;
private TextView lblItemDetail = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the fragment layout
View rootView = inflater.inflate(R.layout.fragments_detail_fragment, container, false);
lblItemDetail = (TextView) rootView.findViewById(R.id.lbl_itemDetail);
//at this point the TextView is not null===>see L0g.i
Log.i(DETAIL_FRAG_TAG, " ---MyDetailFragment---oncreateView()--lblItemDetail =[" + lblItemDetail + "]");
// get the fragment activity context
appContext = this.getActivity();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
/**
* show the details of the item selected on the listFragment.
* #param itemDetail - the details of the item selected on ListFragment.
*/
public void showLstItemDetail(String itemDetail) {
if (lblItemDetail != null) {
// the View to show Text should not be Null.
lblItemDetail.setText(itemDetail);
}
//at this point calling this method shows
that the `TextView` is Null yet it's
initialized in the
oncreate() as a class member variable ---why am i
getting Null after the `oncreate` is finished.
Log.i(DETAIL_FRAG_TAG, "------showItemDetail---------msg=[" + itemDetail + "] txt=[" + lblItemDetail + "]");
}
//when I create an instance of `MYDetailFragment` and call the method to show the details of item Selected on the `DetailFragment` the `TextView` will be null. Why?
MYDetailFragment detailFrag = new MyDetailFragment();
detailFrag.showLstItemDetail("Selected List Item");
Please verify the following tutorial about fragments if any useful information Click here
during those two lines:
MYDetailFragment detailFrag = new MyDetailFragment();
detailFrag.showLstItemDetail("Selected List Item");
the onCreateView() was not called yet. That means the fragment rootView was never created and the TextView was never created YET!
the view will only be created after you use a fragment transaction, to put that fragment in the layout, the fragment will then be attached to the activity (onAttach()) and after a few more callbacks onCreateView() will be called. Only then anything can be set to it.
The standard good practice to pass parameters to a fragment is using a Bundle. Look an example code:
on the activity:
MYDetailFragment detailFrag = new MYDetailFragment();
Bundle b = new Bundle();
detailFrag.setArguments(b);
b.putString("detail", value);
// then proceed to the fragment transaction
then on your fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the fragment layout
View rootView = inflater.inflate(R.layout.fragments_detail_fragment, container, false);
lblItemDetail = (TextView) rootView.findViewById(R.id.lbl_itemDetail);
Bundle b = getArguments();
lblItemDetail.setText(b.getString("details"));
Related
In my app, I have multiple instances of the same fragment, ActivityFragment. In each fragment, there is an activity_text textview. When the fragment is added to the layout, I want to set the activity_text textview within that fragment during onCreate. However, when I try to do this, every ActivityFragment onscreen will have their activity_text textview changed.
Is there any way that I can limit setText to within the scope of an individual fragment without using unique Tags or IDs for each fragment?
Here is my ActivityFragment class:
public static class ActivityFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, Bundle savedInstanceState) {
final View fragment1 = inflater.inflate(R.layout.activity_fragment, container, false);
final TextView activityText = (TextView) fragment1.findViewById(R.id.activity_text);
//Calling setText changes the activityText Textview in every fragment onscreen
activityText.setText(text);
return fragment1;
}
}
Here is my MainActivity class:
public class MainActivity extends FragmentActivity {
Static String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i != 5; i++) {
//This ensures each fragment receives a unique String
text = "success" + i;
ActivityFragment myFragment = new ActivityFragment();
getFragmentManager().beginTransaction()
.add(R.id.fragment_container, myFragment).commit();
}
}
}
It looks like there's two problems with your code.
The first is that you're using a static String text to transmit information from your Activity to your Fragments. In general, this is not a good idea; if you need to "pass" something from your Activity to your Fragment at the time it's constructed, you should use Fragment.setArguments(Bundle) to do that.
The second is that you seem to have a misconception about the timing of FragmentTransactions. Your for loop changes the value of text and then .commit()s a new fragment five times. But these transactions are asynchronous, and the fragment lifecycle has its own timeline. So your onCreateView() will actually wind up being called after your activity onCreate() has finished, and so each of your five fragments gets the same value from text.
Here's how I'd solve it:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i != 5; i++) {
Bundle args = new Bundle();
args.putString("text", "success" + i);
ActivityFragment myFragment = new ActivityFragment();
myFragment.setArguments(args);
getFragmentManager().beginTransaction()
.add(R.id.fragment_container, myFragment).commit();
}
}
public static class ActivityFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, Bundle savedInstanceState) {
final View fragment1 = inflater.inflate(R.layout.activity_fragment, container, false);
final TextView activityText = (TextView) fragment1.findViewById(R.id.activity_text);
String text = getArguments().getString("text");
activityText.setText(text);
return fragment1;
}
}
}
Your issue have nothing to do with the scope of the textview.
Each fragment is individually setting the textView to text, as you instructed them to do so. That happens because onCreateView gets called much latter, after all the fragment transactions happened.
On your code you put the comment: //This ensures each fragment receives a unique String, actually, there's nothing there ensuring that fragments are receiving anything. I recommend you reading what a static means in Java. On that for-loop you change the value of text 5 times in a row and the last value is "success4".
The correct way to pass parameters to a fragment is via a Bundle added calling the methong setArguments(Bundle)
I searched and this answer here https://stackoverflow.com/a/35737232/906362 shows very well explained how to do that. The gist is something like this:
for (int i = 0; i != 5; i++) {
ActivityFragment myFragment = new ActivityFragment();
Bundle b = new Bundle();
// This really ensures each fragment receives a unique String
b.putString("text", "success" + i)
myFragment.setArguments(b);
getFragmentManager().beginTransaction()
.add(R.id.fragment_container, myFragment).commit();
}
and then to get this value on the fragment:
TextView activityText = (TextView) fragment1.findViewById(R.id.activity_text);
activityText.setText(getArguments().getString("text");
I have a button inside of a fragment that I need to be able to access in the activity to change it's text. I am using this code in my main activity:
CategoryFragment frag = new CategoryFragment();
getSupportFragmentManager().beginTransaction().add(R.id.activity_main, frag).commit();
frag.setButtonText(i);
The problem is the button is never initialized using the onCreateView() method (that method never even gets called) which causes a null pointer exception. I tried adding an onCreate() method in the fragment, which gets called, but I have to get the view in order to initialize my button. Since the view hasn't yet been initialized, I get another null pointer exception from the view. Here is my best attempt at the onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
button = (Button) getView().findViewById(R.id.buttonFrag);
}
In OnCreateView() do like this :
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.yout_layout, container, false);
button = (Button) rootView.findViewById(R.id.buttonFrag);
return rootView;
}
You have completely misunderstood the way Fragment and Activity work with each other. An Activity mainly has the duty to "show" the Fragment, and you need to initialize the Button using your CategoryFragment class.
Override Category Fragment's onActivityCreated() and then add the following:
Button button = (Button) getView.findViewById(R.id.your_views_id);
button.setButton("Voila");
Study about Activity and Fragment Interaction. This might help u. http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/
You can use “static factory method” Refer following code
public class CategoryFragment extends Fragment {
/**
* Static factory method that takes an int parameter,
* initializes the fragment's arguments, and returns the
* new fragment to the client.
*/
public static CategoryFragment newInstance(String i) {
CategoryFragment f = new CategoryFragment();
Bundle args = new Bundle();
args.putInt("buttonText", i);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam = getArguments().getString("buttonText");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_category, container, false);
Button b=(Button) view.findViewById(R.id.button);
b.setText(mParam);
return view;
}
}
and from your activity just call
getSupportFragmentManager().beginTransaction().add(R.id.activity_main, CategoryFragment.newInstance(i)).commit();
I am using I am using view pager and fragments in my project,
I am trying to set title of Actionbar from fragment class.
My following code showing title of next fragment on current visible fragment.
can you have any ideas how to show current visible fragments title in Action Bar
public class MyFragment extends Fragment {
TextView textView;
int mCurrentPage;
String name = null, data = null;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = data.getInt("current_page", 0);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setData();
View view = inflater.inflate(R.layout.fragment_Item, container, false);
textView = (TextView) view.findViewById(R.id.fragmentItemTextView);
textView.setText(data);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(name);
//this sets title of actionbar
//but it set name of next item's name in actionbar
return view;
}
void setData() {
//here I call database to get name of item and data of item
ItemProcess sp = new ItemProcess(getActivity().getApplicationContext());
ArrayList temp;
temp = sp.getSingleItem(mCurrentPage);
name = temp.get(0).getmItemName();
data = temp.get(0).getmItemData();
}
}
but it set name of next item's name in actionbar.
By default, ViewPager Adapter will create the current and the next fragment view for you, refer to:
Book "Android.Programming.The.Big.Nerd.Ranch.Guide" P207
Life cycle methods:
// when first in page0
D/Adapter (25946): getItem(0)
D/Adapter (25946): getItem(1)
D/Fragment1(25946): newInstance(Hello World, I'm li2.)
D/Fragment0(25946): onAttach()
D/Fragment0(25946): onCreate()
D/Fragment0(25946): onCreateView()
D/Fragment1(25946): onAttach()
D/Fragment1(25946): onCreate()
D/Fragment1(25946): onCreateView() // that's why it set name of next item.
So it would be better to update ActionBar title in Activity:
// init title
mViewPager.setCurrentItem(i);
// update title
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
setTitle(...);
}
});
it is because viewpager loads onCreateView method of next fragment after calling it on current fragment, and you can't set viewPagerOffset limit to 0.
you can change your action bar title from your fragment by this code :
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
m_iAmVisible = isVisibleToUser;
if (m_iAmVisible) {
Log.d(localTAG, "this fragment is now visible");
//change your actionbartitle
} else {
Log.d(localTAG, "this fragment is now invisible");
}
}
The context is:
I have an activity consisting of a fragment where there is a form to enter a date and a flight number. There are no other fragments there.
On click of a button, a request is made to a webservice.
A List of Flight Objects is returned from the webservice.
A custom ArrayAdapter is created for each row in the listFragment.
Show the results in a ListFragment in the same Activity on the frontend.
FlightResultAdapter.java:
public class FlightResultAdapter extends ArrayAdapter<Flight>{
public FlightResultAdapter(Context context, List<Flight> flights) {
super(context, R.layout.item_flight, flights);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Flight flight = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_flight, parent, false);
}
//Set the content of the custom row layout
TextView tvFlightNum = (TextView) convertView.findViewById(R.id.tvFlightNum);
tvFlightNum.setText(flight.getNumber());
return convertView;
}
}
Note: ListFragment has a default layout that consists of a single list view. Source
So I do not need a layout file for the list.
MyActivity.java: A list of objects (flightList.getFlight) is used to create the CustomListAdapter. This code is inside a function that is triggered on an OnClick.
FlightResultAdapter adapter =
new FlightResultAdapter(getApplicationContext(), flightList.getFlight());
FlightFragment.java
public class FlightFragment extends ListFragment {
private List<Flight> flight_items;
public FlightFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
flight_items = new ArrayList<Flight>();
//Initialise the list adapter and set
FlightResultAdapter adapter = new FlightResultAdapter(getActivity(), flight_items);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Flight flight = flight_items.get(position);
Toast.makeText(getActivity(), flight.getNumber(), Toast.LENGTH_LONG).show();
}
}
So what I'm not getting is how to Show the FlightFragment on MyActivity.
Furthermore how to connect it so results are displayed: I think setListAdapter is used?
Update: Connecting the Fragment to the Activity
1. Add a FrameLayout to the activity layout, or other fragment layout
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
2. Use the FragmentManager to call the Fragment programmatically:
//Create the adapter here
FlightResultAdapter adapter = new FlightResultAdapter(getApplicationContext(), flightList.getFlight());
//Get the Fragment here and set the ListAdapter
FlightFragment ff = new FlightFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
ff.setArguments(getIntent().getExtras());
ff.setListAdapter(adapter);
if (findViewById(R.id.fragment_container) != null) {
//Send the Data to the fragment - Need Help Here
Bundle bundle = new Bundle();
//Show the Fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, ff);
fragmentTransaction.commit();
}
So the Fragment's OnCreate Method is being called, but the list is empty because I am not passing the Flight Object to the Fragment. How can I do this?
How can I pass the List object to the Fragment?
Because List contains Flight custom class object. so it's not possible to pass it directly.
To pass List<Flight> object:
1. Implement Serializable in Flight class.
2. Use Bundle.putSerializable for sending object from Activity to FlightFragment :
Bundle bundle = getIntent().getExtras();
bundle.putSerializable("flightList", flightList.getFlight());
ff.setArguments(bundle);
...
3. In FlightFragment class override onCreateView method and getArguments method:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
List<Flight> flightList=(List<Flight>)args.getSerializable("flightList");
....
return super.onCreateView(inflater, container, savedInstanceState);
}
I have an app, that deals with fragments and ViewPager. I have three fragments in a ViewPager. When you switch between them, it always causes the other two fragments to call their's onCreateView methods. How to do it only once, only when FragmentActivity is created???
I've read some questions and tried the solutions, but the fragments still have the same behavior.
ListFragment onCreate called twice
onCreate() and onCreateView() invokes a lot more than required (Fragments)
Here is some code, if it helps you, guys:
MainActivity:
public class StartingActivity extends FragmentActivity implements View.OnClickListener {
ViewPager viewPager;
CirclePageIndicator pageIndicator;
Button discount;
Button qrCode;
Button pay;
TabHost tabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starting_layout);
viewPager = (ViewPager) findViewById(R.id.pager);
if (savedInstanceState == null) {
Fragment firstPage = Fragment.instantiate(this, FindTovarFragment.class.getName());
Fragment secondPage = Fragment.instantiate(this, MainWindowActivity.class.getName());
Fragment thirdPage = Fragment.instantiate(this, MapActivity.class.getName());
if ((firstPage != null && !firstPage.isDetached())|| (secondPage != null && !secondPage.isDetached()) || (thirdPage != null && !thirdPage.isDetached())) {
List<Fragment> viewPagerFragments = new ArrayList<Fragment>();
viewPagerFragments.add(firstPage);
viewPagerFragments.add(secondPage);
viewPagerFragments.add(thirdPage);
PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager(), viewPagerFragments);
viewPager.setAdapter(pageAdapter);
pageIndicator = (CirclePageIndicator) findViewById(R.id.circle);
pageIndicator.setViewPager(viewPager);
pageIndicator.setCurrentItem(pageAdapter.getCount() - 2);
}
}
}
MapActivity:
public class MapActivity extends Fragment implements OnMyLocationListener {
//Тэг для логов
private static final String TAG = "MapActivity";
List<Address> addressList;
private static final String STRING_LOCATION = "";
ArrayList<TorgCentr> randomTorgCentr;
ArrayList<String> torgCentrNames;
Context context;
AutoCompleteTextView searchTorgCentr;
OverlayManager overlayManager;
MapController mapController;
TextView textView;
double longitude;
double latitude;
double itemLongitude;
double itemLatitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "MapActivity onCreateView");
View view = (LinearLayout) inflater.inflate(R.layout.map_layout, container, false);
final MapView mapView = (MapView) view.findViewById(R.id.map);
textView = (TextView) view.findViewById(R.id.searchlocation);
searchTorgCentr = (AutoCompleteTextView) view.findViewById(R.id.autoCompleteTextView);
mapView.showBuiltInScreenButtons(true);
mapController = mapView.getMapController();
context = getActivity();
return view;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "MapActivity onCreate");
}
public void onActivityCreated(Bundle savedInstanceState) {
Log.d(TAG, "MapActivity onActivityCreated");
context = getActivity();
SetRightMapDisplayAddress rightMapDisplayAddress = new SetRightMapDisplayAddress();
rightMapDisplayAddress.execute(STRING_LOCATION);
DownloadSuperMarketsArray superMarketsArray = new DownloadSuperMarketsArray();
superMarketsArray.execute();
overlayManager = mapController.getOverlayManager();
overlayManager.getMyLocation().setEnabled(false);
super.onActivityCreated(savedInstanceState);
}
Second Fragment:
public class MainWindowActivity extends Fragment {
private static final String TAG = "MainWindowActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "MainWindowActivity onCreateView");
View view = (RelativeLayout) inflater.inflate(R.layout.main_window_layout, container, false);
if (container == null) {
return null;
}
return view;
}
}
And the third one:
public class FindTovarFragment extends Fragment {
private static final String TAG= "FindTovarFragment";
Context context;
ArrayList<Category> categories;
Spinner categoryContainer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "FindTovarFragment onCreateView");
View view = (LinearLayout) inflater.inflate(R.layout.find_tovar_main_layout, container, false);
categoryContainer = (Spinner) view.findViewById(R.id.category);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "FindTovarFragment onActivityCreated");
DownloadCategory downloadCategory = new DownloadCategory();
downloadCategory.execute();
}
Logs for MapActivity:
06-20 11:06:37.709: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:06:37.709: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:06:38.509: DEBUG/MapActivity(1290): MapActivity onActivityCreated
Then again and again:
06-20 11:07:53.239: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:07:53.239: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:07:53.429: DEBUG/MapActivity(1290): MapActivity onActivityCreated
06-20 11:08:23.029: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:08:23.039: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:08:23.269: DEBUG/MapActivity(1290): MapActivity onActivityCreated
Thank you very much in advance.
ViewPager retain in memory 1 page by default, to either side of the current page. So it would not re-create those pages when swiping 1 page left/right of the current page. But when swipe more than 1 pages to left/right, it would re-create those page again, hence called OnCreateView(), OnCreate().
If app uses few pages 3, you can increase the number of pages to retain by calling,
mViewPager.setOffscreenPageLimit(2);
Described here
I would change your architecture for this one on the android developer documentation:
http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html
but I would change some things...
1-I would change this method:
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
return v;
}
For something like this where we decide which fragment you populate depending the position of the viewPager:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
SupportFragmentManager ft = getChildFragmentManager().beginTransaction();
String tag = "";
Fragment fragment = null;
switch (mNum) {
case 0:
fragment = new MyFragmentZero();
tag = FragmentTags.TAG_0;
break;
case 1:
fragment = new MyFragmentOne();
tag = FragmentTags.TAG_3;
break;
case 2:
fragment = new MyFragmentTwo();
tag = FragmentTags.TAG_2;
break;
default:
break;
}
/*OPTIONAL We can pass arguments to the fragments
Bundle args = new Bundle();
args.putInt(Arguments.ARG_POSITION, mNum);
fragment.setArguments(args);*/
//Place the fragment in the container
ft.replace(R.id.fragment_container fragment, tag);
ft.commit();
//You need a base layout for all fragment and use nested fragments later or you can define the layout for each position(mNum) inside the switch.
return inflater.inflate(R.layout.fragment_layout_default_for_all_views, container,
false);
}
Like this you will have a good architecture and once it is working like this should be fine.
Anyway you must know how the viewPager works populating the fragment in the different positions.
When you start on the position 0, then the fragment on the position 0 and the one of the position 1 are created.
Then when you swipe to the position 1 the fragment on the 2 position is created, so you have now the three fragments created on the different positions (0,1,2..assuming you have only 3 pages on the viewPager).
We swipe to the position 2, the last one, and the fragment on the first position (0) get destroy, so we have now the fragments on the positions 2 and 3.
I hope it helped and let me know if you have any problem. Cheers
Finally I was able to figure it out. Just need to override the destroyItem method so that it won't destroy objects. Hope this is going to be useful for someone.
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
Log.d(TAG, "destroy!");
}