How to save and restore custom arrayadapter data when switching fragments - android

I've tried different answers on this forum that are related to my problem but none seem to work for me.
ArrayAdapter Class
public class UserAdapter extends ArrayAdapter<User> {
public UserAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
private static class ViewHolder {
TextView water;
TextView amount;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.card, parent, false);
viewHolder.water = (TextView) convertView.findViewById(R.id.WaterConsumed);
viewHolder.amount = (TextView) convertView.findViewById(R.id.WaterAmount);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.water.setText(user.waterconsum);
viewHolder.amount.setText(user.amount);
// Return the completed view to render on screen
return convertView;
}
User Class
public class User implements Serializable{
String waterconsum;
String amount;
public User(String waterconsum, String amount) {
this.waterconsum = waterconsum;
this.amount = amount;
}
One of the fragment class that shows the data
public class WaterFragment extends Fragment {
ArrayList<User> arrayOfUsers = new ArrayList<User>();
UserAdapter adapter;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setRetainInstance(true);
if (savedInstanceState != null) {
arrayOfUsers = (ArrayList<User>) savedInstanceState.getSerializable("List");
}
return view = inflater.inflate(R.layout.water, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
Button button = (Button) view.findViewById(R.id.additem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
adapter = new UserAdapter(getActivity(), arrayOfUsers);
ListView listView = (ListView) view.findViewById(R.id.listofitems);
if (listView.getAdapter() != null) {
listView.onRestoreInstanceState(savedInstanceState);
} else {
listView.setAdapter(adapter);
}
}
protected void showInputDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
final View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString();
addItems(text);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void addItems(String text) {
arrayOfUsers.add(new User("Water Consumed Today", text));
}
#Override
public void onSaveInstanceState(Bundle state) {
state.putSerializable("List", arrayOfUsers);
super.onSaveInstanceState(state);
}
Whenever i switch between different fragments, the array data is always reset. So im not sure on how to go about solving this, i've tried various solutions that involved saving the fragment state and the array data but none seem to work so far.
EDIT: Fragment Handler class
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
bottomBar = BottomBar.attach(this, savedInstanceState);
bottomBar.setItemsFromMenu(R.menu.three_buttons_menu, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.Calendar) {
CalendarFragment f = new CalendarFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f).commit();
} else if (menuItemId == R.id.Water) {
WaterFragment wf = new WaterFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,wf).commit();
} else if (menuItemId == R.id.Advice) {
AdviceFragment af = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, af).commit();
} else if (menuItemId == R.id.Diary) {
AdviceFragment af = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, af).commit();
} else if (menuItemId == R.id.Help) {
AdviceFragment af = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, af).commit();
}
getFragmentManager().executePendingTransactions();
}
});

create your adaptor only once in onCreate of your fragment.
and in your onViewCreated set this adaptor to listview.
private UserAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(adapter==null)
adapter = new UserAdapter(getActivity(), arrayOfUsers);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView listView = (ListView) view.findViewById(R.id.listofitems);
listView.setAdapter(adapter);
}
and whenever data changes add new items in adapter and call notifyDataSetChanged.
UPDATE: From your Fragment Handler class, you are creating new instance everytime you are replacing fragment like
CalendarFragment f = new CalendarFragment();
I'll suggest you to do like this..
private CalendarFragment calenderFragment;
private WaterFragment waterFragment;
private AdviceFragment adviceFragment;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
calenderFragment = new CalendarFragment();
waterFragment = new WaterFragment();
adviceFragment = new AdviceFragment();
bottomBar = BottomBar.attach(this, savedInstanceState);
bottomBar.setItemsFromMenu(R.menu.three_buttons_menu, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.Calendar) {
if(calenderFragment==null)
calenderFragment = new CalendarFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, calenderFragment)
.commit();
} else if (menuItemId == R.id.Water) {
if(waterFragment==null)
waterFragment = new WaterFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, waterFragment)
.commit();
} else if (menuItemId == R.id.Advice) {
if(adviceFragment==null)
adviceFragment = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, adviceFragment )
.commit();
} else if (menuItemId == R.id.Diary) {
if(adviceFragment==null)
adviceFragment = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, adviceFragment )
.commit();
} else if (menuItemId == R.id.Help) {
if(adviceFragment==null)
adviceFragment = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, adviceFragment )
.commit();
}
getFragmentManager().executePendingTransactions();
}
});

Related

Open a fragment from a fragment's fragment?

I have a Fragment with a ListView. When I click one of the item, a new Fragment is opened, and from this Fragment I want to open a new Fragment witha a Button.
I try to write the code, but it's a mess. When a click the Button, the program is crashed.
Should I use another way? I call the third Fragment like the second
Activity:
public class Grade extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSt
ate);
setContentView(R.layout.activity_grade);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
new Objectlist()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new Objectlist();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new Examlist();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
selectedFragment).commit();
return true;
}
};
}
1st Fragment:
public class Objectlist extends Fragment {
View v;
DB mydb;
ListView listView;
private String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Gradeview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
String jegyAtlag="0";
Cursor data = mydb.JegyekAtlaga(teszt);
while (data.moveToNext()) jegyAtlag=data.getString(0);
String jegyDarab="0";
data = mydb.JegyekDarabszama(teszt);
while (data.moveToNext()) jegyDarab=data.getString(0);
if (jegyAtlag.equals("") || jegyDarab.equals(""))
else {
bundle.putString("Tantárgy átlaga", jegyAtlag);
bundle.putString("Tantárgy darabszáma", jegyDarab);
TextView jegyekHeader = (TextView) v.findViewById(R.id.header);
jegyekHeader.setText(teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
ListView listaNezet = (ListView) v.findViewById(R.id.Gradeview);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
}
);
}
return v;
}
}
2nd Fragment:
public class targyAdatok extends Fragment {
public targyAdatok() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_targy_adatok, container, false);
Button elemzes = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.targyAdatok,jegyekAllando);
FragTan.commit();
}
});
return v;
}
}
3rd Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("Tantárgy átlaga");
String jegyDarabSt = bundle.getString("Tantárgy darabszáma");
return rootView;
}
}
I solved my problem. The problem was that a replaced the wrong fragment. Every time I have to replace the Activity's Fragment.

How to use the instance of a same Fragment with different data across pages of a viewPager?

I am using different instance of the same fragment in a viewPager.Because every page does the same thing but only differ by data.But the problem is viewPager shows same data in all pages.Creating new instance in the adapter does not change the data.All what i want is when the user swipes to new page it shows a new instance of the same fragment as shown in the adapter respective to the position.
Here is the adapter :
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
ListViewFragment f = ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=al-jazeera-english&sortBy=top&apiKey=6cde");
return f;
}
else if (position == 1){
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=abc-news-au&sortBy=top&apiKey=6cde");
}
else
{
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=6cde");
}
}
#Override
public int getCount() {
return 3;
}
}
And this activity holds the viewPager:
public class WorldNews extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_world_news);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
FragmentPageAdapter adapter = new FragmentPageAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
}
}
Here is the code for the Fragment(Just a normal fragment which implements loader):
public class ListViewFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<GameNews>> {
public static ListViewFragment newInstance(String url) {
Log.d("ListViewFragment","newInstance created");
ListViewFragment f = new ListViewFragment();
// Supply url input as an argument.
Bundle args = new Bundle();
args.putString("url", url);
f.setArguments(args);
return f;
}
private AdView mAdView;
AdRequest adRequest;
ListAdapter adapter ;
private View progressBar;
final private int game_loader = 0;
ArrayList<String> urls = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list_view, container, false);
//Log.d("ListViewFragment","" + getArguments().getString("url"));
mAdView = (AdView) rootView.findViewById(R.id.adView);
adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
final LinearLayout emptyView = (LinearLayout) rootView.findViewById(R.id.no_internet_view);
emptyView.setVisibility(View.INVISIBLE);
//Getting listView
final ListView gameListView = (ListView) rootView.findViewById(R.id.listView);
//progress bar finding
progressBar = rootView.findViewById(R.id.progress_bar);
ArrayList<GameNews> gameList = new ArrayList<>();
Button retryButton = (Button) rootView.findViewById(R.id.retry_button);
//Making a new arrayAdapter
adapter = new ListAdapter(getActivity(),gameList);
//Connecting ArrayAdapter to ListView
gameListView.setAdapter(adapter);
urls.add(getArguments().getString("url"));
Log.d("ListViewFragment","" + urls.get(0));
if(isConnected())
{
getActivity().getLoaderManager().initLoader(game_loader, null, this);
}
else
{
emptyView.setVisibility(View.VISIBLE);
gameListView.setVisibility(View.INVISIBLE);
}
//ListView item click listner
gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
GameNews currentEarthquake = adapter.getItem(i);
String url = currentEarthquake.getUrl();
final Intent intent = new Intent(getContext(), browser.class);
intent.putExtra("Url", url);
startActivity(intent);
}
});
retryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isConnected())
{
mAdView.loadAd(adRequest);
getActivity().getLoaderManager().restartLoader(game_loader, null, ListViewFragment.this);
emptyView.setVisibility(View.INVISIBLE);
gameListView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
Log.d("General news","retry clicked");
}
}
});
return rootView;
}
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
#Override
public Loader<List<GameNews>> onCreateLoader(int i, Bundle bundle) {
AdManager manager = new AdManager(getActivity());
return new GameLoader(getActivity(),urls,1000);
}
#Override
public void onLoadFinished(Loader<List<GameNews>> loader, List<GameNews> games) {
progressBar.setVisibility(View.INVISIBLE);
adapter.clear();
if(games == null)
{
return;
}
adapter.addAll(games);
}
#Override
public void onLoaderReset(Loader<List<GameNews>> loader) {
adapter.clear();
}
public void setUrl(String url)
{
this.urls.add(url);
}
}
Try to use FragmentStatePagerAdapter https://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter instead of FragmentPagerAdapter. Difference between them: here for example.

Fragment disappearing when coming back from another Fragment

I have a viewpager with 3 fragments to make a swipeable widget. When I first load the app they show properly and all the click events work as expected. Same with hitting the back button after clicking each OnClick, sends me back to landingpagenotlogged in and the viewpager/fragments are displayed as expected. My problem is when I hit my menu button and come back to the landing page my view pager disappears.
I did try to use getChildFragmentManager() when setting the adapter and it works but then my onClick events do not work any more as I get no view to id *******.
I have also tried to place the adapter in the onResume(); with no luck at all.
Along with the viewpager, my viewpagerindicator is not working for the homewidget but working for the carousel. Not sure if that is the code or the layout. But I set it up the same way as the carousel and still not seeing it within the screen when run.
Landingpagenotlogged
public class LandingPageFragmentLoggedOut extends LandingPageFragment {
private static final String TAG = LandingPageFragmentLoggedOut.class.getSimpleName();
private ViewPager viewPager;
private RelativeLayout myStoreTab;
private Button signIn;
private final static Fragment instance = new LandingPageFragmentLoggedOut();
LoggedOutWidgetAdapter mAdapter;
ViewPager mPager;
public static final int ITEMS = 3;
static public Fragment getInstance() {
return instance;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
setShoppingListFocusChangeListener();
setSignInBtnClickListener();
super.setViewPagerMotionListeners(viewPager);
setMenuTouchListener();
setTabClickListener();
return view;
}
#Override
protected void inflateFragmentView(LayoutInflater inflater, ViewGroup container) {
view = inflater.inflate(R.layout.landingpage_not_logged_in, container,
false);
RelativeLayout thisLayout = (RelativeLayout) view
.findViewById(R.id.landingpage_logged_out_parent_layout);
TileBackground.fixBackgroundRepeat(thisLayout);
imgArch = view.findViewById(R.id.frag_tab);
}
private void setSignInBtnClickListener() {
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> params = new HashMap<>();
Intent intent = new Intent(getActivity(), SignInActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(
R.anim.enter_in_from_bottom, R.anim.anim_static);
params.put("Module", "Home");
FlurryAgent.logEvent(FlurryConstants.GOTO_SIGN_IN, params);
}
});
}
private void setTabClickListener() {
myStoreTab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tabSelection = 1;
tabSelectionListener.onTabSelectionListener(tabSelection);
toggleStoreTabIndicator(1);
}
});
}
#Override
#SuppressLint("WrongViewCast")
protected void setUIreferences() {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
overlay = view.findViewById(R.id.landingpage_screenOverlay);
indicator = (LinePageIndicator) view.findViewById(R.id.image_slider_indicator);
this.signIn = (Button) view.findViewById(R.id.landingpg_sign_in_btn);
shoppingListBtn = (ImageView) view.findViewById(R.id.icnlistoptions);
myStoreTab = (RelativeLayout) view.findViewById(R.id.frag_tab);
menuButton = (Button) view.findViewById(R.id.imgBanner_list);
logoButton = (ImageView) view.findViewById(R.id.headerLogo);
addShoppingListItemWidget = (EditText) view.findViewById(R.id.editAddItemNotLoggedIn);
addShoppingListItemWidget.setOnKeyListener(null);
addedItemConfirmation = view.findViewById(R.id.addedItemConfirmation);
imgScanner = (ImageView) view.findViewById(R.id.imgScannerNotLoggedIn);
toggleScannerVisibility(true);
itemAddedText = (TextView) view.findViewById(R.id.item_added_text);
weeklyAdImg = (ImageView) view.findViewById(R.id.weeklyad_img);
defaultWelcomeMsg = (ImageView) view.findViewById(R.id.landing_page_default_img);
setWeeklyAdThumbNail();
if(imgUrl!=null)
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
//setWeeklyAdOnClickListener();
setWeeklyAdClickListener();
couponsGrid = view.findViewById(R.id.coupons_grid);
couponsPlaceholderImg = (ImageView) view.findViewById(R.id.feat_coupons);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
itemAddedText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
}
imgScanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
mShoppingListAdd = (RelativeLayout) view.findViewById(R.id.shoppinglis_shortcut);
mShoppingListAdd.setVisibility(View.GONE);
mAdapter = new LoggedOutWidgetAdapter(getFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(mAdapter);
LinePageIndicator mLoggedOutWidgetIndicator = (LinePageIndicator)view.findViewById(R.id.homewidgetLoggedOutIndicator);
mLoggedOutWidgetIndicator.setViewPager(mPager);
}
// MSM - 214
private void setWeeklyAdThumbNail() {
try {
if (LocalDb.getStoreId() != LocalDb.DEFAULT_VAL) {
if (weeklyAdBundle != null && !weeklyAdBundle.isEmpty()) {
//MSM - 155
if (!Utils.isStringNull(weeklyAdBundle.getString("WeeklyAdThumbnail"))) {
Log.e("BANNER ID SET: ", weeklyAdBundle.getString("WeeklyAdThumbnail"));
imgUrl = weeklyAdBundle.getString("WeeklyAdThumbnail");
}
else
imgUrl = weeklyAdBundle.getString("0FirstThumbnail");
}
}
if (urls == null || !urls.contains(imgUrl)) {
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
}
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void sendRequest() {
if (CheckNetworkConnection.isConnectionAvailable(activity)) {
jsonParser = new CarouselJSONParser(this);
jsonParser.execute();
} else {
setDefaultOfflineImage();
weeklyAdImg.setImageResource(R.drawable.img_ad_default);
// TODO Set OFFLINE message here
}
}
#Override
public void setCarouselData(ArrayList<CarouselImageData> imageDatas) {
Log.v(TAG, "Set Carousel Data hit");
if (imageDatas != null) {
this.advertisements = imageDatas;
runnable(advertisements.size());
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
viewPager
.setAdapter(new ImageSliderAdapter(activity, imageDatas, this, weeklyAdBundle));
indicator.setViewPager(viewPager);
if (isFirstTimeLaunched) {
fadeInWelcomMsg();
Log.v(TAG, "first time launched, welcome message initaited");
} else {
viewPager.setVisibility(View.VISIBLE);
indicator.setVisibility(View.VISIBLE);
Log.v(TAG, "Returning user, viewpager set visible");
}
} else {
setDefaultOfflineImage();
}
}
#Override
public void onResume() {
if (LocalDb.isLoggedIn()) {
Fragment fragment = new LandingPageFragment();
launchNavigationItemFragment(fragment);
}
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
if (viewPager == null) {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
}
mAdapter = new LoggedOutWidgetAdapter(getChildFragmentManager());
super.onResume();
if (newItemIsAdded) {
onShoppingListResult();
}
// addShoppingListItemWidget.clearFocus();
}
#Override
void runnable(final int size) {
handler = new Handler();
animateViewPager = new Runnable() {
#Override
public void run() {
if (!pageIsSliding) {
if (viewPager.getCurrentItem() == size - 1) {
viewPager.setCurrentItem(0);
} else {
viewPager.setCurrentItem(
viewPager.getCurrentItem() + 1, true);
}
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
}
}
};
}
#Override
void toggleStoreTabIndicator(int tab) {
if (storeTabIsClosed) {
storeTabIsClosed = false;
imgArch.setBackgroundResource(R.drawable.img_single_arch_my_store);
} else {
storeTabIsClosed = true;
imgArch.setBackgroundResource(R.drawable.img_arch);
}
}
#Override
protected void setFontsOnTextViews(View view) {
}
#Override
protected void setTabClickListeners() {
}
#Override
public void setViewPagerMotionListeners(ViewPager vPager) {
}
public class LoggedOutWidgetAdapter extends FragmentPagerAdapter {
public LoggedOutWidgetAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ProductLocatorHomeWidgetFragment.init(position);
case 1:
return ProductScanHomeWidgetFragment.init(position);
case 2:
return MyShoppingListHomeWidgetFragment.init(position);
default:
return null;
}
}
#Override
public int getCount() {
return ITEMS;
}
}
}
The three fragments that are tied to the viewpager
ProductLocatorHomeWidgetFragment
public class ProductLocatorHomeWidgetFragment extends Fragment {
int fragVal;
int storeId;
String storeName, storeLat, storeLong, retail_store_id;
TextView mProductLocatorClickZone;
StoreList sList;
public static ProductLocatorHomeWidgetFragment init(int val) {
ProductLocatorHomeWidgetFragment productLocatorFragment = new ProductLocatorHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodLocator", val);
productLocatorFragment.setArguments(args);
return productLocatorFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("prodLocator") : 1;
sList = new StoreList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_locator_search_widget, container, false);
mProductLocatorClickZone = (TextView) layoutView.findViewById(R.id.editSearchItemNotLoggedIn);
mProductLocatorClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sList = LandingPageFragment.storeList;
if(sList.getId() != null){
storeId = Integer.parseInt(sList.getId());
storeLat = sList.getLatitude();
storeLong = sList.getLongitude();
storeName = sList.getName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
else if (sList.getId() == null) {
if (LocalDb.getStoreId() > 0) {
storeId = LocalDb.getStoreId();
storeLat = LocalDb.getStoreLat();
storeLong = LocalDb.getStoreLng();
storeName = LocalDb.getMyStoreName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
}
else {
StoreLocatorDetailsSearchFragment storeLocatorDetailsSearchFragment = new StoreLocatorDetailsSearchFragment();
Bundle b1 = new Bundle();
b1.putInt("currentFragment", 10);
storeLocatorDetailsSearchFragment.setArguments(b1);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, storeLocatorDetailsSearchFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return layoutView;
}
}
MyShoppingListHomeWidgetFragment
public class MyShoppingListHomeWidgetFragment extends Fragment {
int fragVal;
EditText mShoppingListClickZone;
ImageView mShoppinglistScanClickZone;
public static MyShoppingListHomeWidgetFragment init(int val) {
MyShoppingListHomeWidgetFragment myShoppingListFragment = new MyShoppingListHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("myShoppingList", val);
myShoppingListFragment.setArguments(args);
return myShoppingListFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("myShoppingList") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.shopping_list_widget, container, false);
mShoppingListClickZone = (EditText) layoutView.findViewById(R.id.editAddItemNotLoggedIn);
mShoppingListClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShoppingListItemsFragment shoppingListItemsFragment = new ShoppingListItemsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, shoppingListItemsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
mShoppinglistScanClickZone = (ImageView) layoutView.findViewById(R.id.imgScannerNotLoggedIn);
mShoppinglistScanClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
return layoutView;
}
}
ProductScanHomeWidgetFragment
public class ProductScanHomeWidgetFragment extends Fragment {
int fragVal;
LinearLayout mCouponSearchClickZone, mRefillPrescriptionClickZone;
View mDivider;
public static ProductScanHomeWidgetFragment init(int val) {
ProductScanHomeWidgetFragment productScanFragment = new ProductScanHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodScan", val);
productScanFragment.setArguments(args);
return productScanFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("prodScan") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_scan_widget, container, false);
mRefillPrescriptionClickZone = (LinearLayout) layoutView.findViewById(R.id.refillPrescriptionClickZone);
mCouponSearchClickZone = (LinearLayout) layoutView.findViewById(R.id.couponSearchClickZone);
mCouponSearchClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ECouponsViewFragment eCouponsViewFragment = new ECouponsViewFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, eCouponsViewFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
if (LocalDb.getBannerSupportRefillPrescriptions().equalsIgnoreCase(
UtilConstants.KEY_WORD_FALSE)) {
mDivider = layoutView.findViewById(R.id.divider);
mDivider.setVisibility(View.GONE);
mRefillPrescriptionClickZone.setVisibility(View.GONE);
} else {
mRefillPrescriptionClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPharmacyFragment addPharmacyFragment = new AddPharmacyFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, addPharmacyFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
return layoutView;
}
}
I was able to solve this using a FragmentStatePagerAdapter and not the FragmentPagerAdapter.
So I removed the old FragmentPagerAdapter in LadingPageLoggedOut and replaced it with
inal String [] fragmentClasses = {"com.supervalu.mobile.android.HomeScreenWidget.ProductLocatorHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.ProductScanHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.MyShoppingListHomeWidgetFragment"};
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
Fragment fragmentAtPosition = null;
// Check to make sure that your array is not null, size is greater than 0 ,
// current position is greater than equal to 0, and position is less than length
if((fragmentClasses != null) && (fragmentClasses.length > 0)&&(position >= 0)&& (position < fragmentClasses.length))
{
// Instantiate the Fragment at the current position of the Adapter
fragmentAtPosition = Fragment.instantiate(getContext(), fragmentClasses[position]);
fragmentAtPosition.setRetainInstance(true);
}
return fragmentAtPosition;
}
#Override
public int getCount() {
return fragmentClasses.length;
}
});

Strange behavior of ViewPager

I am using for my Android app PagerSlidingTabStrip and Material Navigation Drawer libraries. I am watching strange behavior of ViewPager - when I am opening it first time, it works normally, but I am opening it again, ViewPager is empty, as without adapter.
MainActivity:
public class MainActivity extends AppCompatActivity {
private Drawer drawer;
private int lastSelection;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private boolean isClickedByUser = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = new DrawerBuilder().withActivity(MainActivity.this)
.withToolbar(toolbar).addDrawerItems(
new PrimaryDrawerItem().withName(R.string.name1)
.withIcon(R.drawable.icon1),
new PrimaryDrawerItem()
.withName(R.string.name2)
.withIcon(R.drawable.icon2))
.withOnDrawerItemClickListener(
new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(AdapterView<?> adapterView, View view,
int position, long id,
IDrawerItem iDrawerItem) {
switch (position) {
case 0:
setTitle(R.string.title1);
break;
case 1:
setTitle(R.string.title2);
break;
}
FragmentManager fManager = getSupportFragmentManager();
FragmentTransaction transaction = fManager.beginTransaction();
transaction.replace(R.id.container, PlaceholderFragment.newInstance(
position)).commitAllowingStateLoss();
lastSelection = position;
return false;
}
})
.build();
drawer.setSelection(0);
}
#Override
public void onBackPressed() {
if (drawer != null && drawer.isDrawerOpen()) {
drawer.closeDrawer();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
drawer.setSelection(lastSelection);
}
}
PlaceholderFragment, in that ViewPager is done:
public class PlaceholderFragment extends Fragment {
private static final String ID = "id";
private int id;
public static PlaceholderFragment newInstance(int id) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch (id) {
case 0:
rootView = inflater.inflate(R.layout.view1, container, false);
break;
case 1:
rootView = inflater.inflate(R.layout.tabs, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.viewPager);
pager.setAdapter(new PagerAdapter(getActivity().getSupportFragmentManager()));
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setShouldExpand(true);
tabs.setIndicatorColorResource(R.color.tab_indicator_color);
tabs.setTextColorResource(R.color.tab_text_color);
break;
default:
break;
}
return rootView;
}
private class PagerAdapter extends FragmentPagerAdapter {
private int[] titlesResIds = { R.string.title1, R.string.title2 };
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return getString(titlesResIds[position]);
}
#Override
public int getCount() {
return titlesResIds.length;
}
#Override
public Fragment getItem(int position) {
return TabFragment.newInstance(position);
}
}
}
TabFragment:
public class TabFragment extends ListFragment {
private static final String ID = "id";
private int id;
public static TabFragment newInstance(int id) {
TabFragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
public TabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://host/")
.build();
String result = null;
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(response));
reader.setLenient(true);
ArrayList<Message> messages = gson.fromJson(reader,
new TypeToken<ArrayList<Message>>(){}.getType());
int i = messages.size() - 1;
while (i != -1) {
if (messages.get(i).getType() != id)
messages.remove(i);
i--;
}
ArrayAdapter adapter = new MyListAdapter(messages);
setListAdapter(adapter);
}
};
asyncTask.execute();
return inflater.inflate(R.layout.fragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent messageIntent = new Intent(getActivity(), MessageActivity.class);
startActivity(messageIntent);
}
private class MyListAdapter extends ArrayAdapter {
private Context context = getActivity();
private ArrayList<Message> messages;
public MyListAdapter(ArrayList<Message> messages) {
super(getActivity(), R.layout.list_adapter);
this.messages = messages;
}
#Override
public int getCount() {
return messages.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_adapter, parent, false);
holder = new ViewHolder();
holder.imageIcon = (ImageView) convertView.findViewById(R.id.list_icon);
holder.textDatetime = (TextView) convertView.findViewById(R.id.list_text_datetime);
holder.textPrimary = (TextView) convertView.findViewById(R.id.list_text_primary);
holder.textSecondary = (TextView) convertView.findViewById(R.id.list_text_secondary);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Message message = messages.get(position);
long timestamp = message.getTimestamp() * 1000;
Date date = new Date(timestamp);
String datetime = new SimpleDateFormat("dd.MM.yyyy hh:mm", Locale.US).format(date);
holder.imageIcon.setImageResource(message.getIcon() == 0 ?
R.drawable.icon1 :
R.drawable.icon2);
holder.textDatetime.setText(datetime);
holder.textPrimary.setText(message.getTitle());
holder.textSecondary.setText(message.getMessage());
return convertView;
}
private class ViewHolder {
ImageView imageIcon;
TextView textDatetime;
TextView textPrimary;
TextView textSecondary;
}
}
}
I already decided my problem. I'm insert method getChildFragmentManager() in my PlaceholderFragment as in this answer - How set ViewPager inside a Fragment.

Android fragments on back exists application

I am having a problem with fragments. I want to start a fragment when I click an item from a Contacts list and then, when I press the phone back button I wanna go back to the contacts list. The fragments starts, but when I press the back button it doesn't go to the contacts lists, it just exists the application and gets to the phone menu.
This is for the contacts list
public class ChatMainActivity extends FragmentActivity{
private static Button btnLogOut;
private static SessionManager sm;
private static ListView listView ;
private List<ContactData> contactsList;
private static class ContactListFragment extends Fragment
{
public static Fragment newInstance(){
ContactListFragment ourList = new ContactListFragment();
return ourList;
}
#Override
public View onCreateView(LayoutInflater inflater,final ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.contactlistfragment,container,true);
listView = (ListView) v.findViewById(R.id.listView);
btnLogOut = (Button) v.findViewById(R.id.btnLogOut);
btnLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SessionManager sm = new SessionManager(v.getContext());
sm.logoutUser();
Intent i = new Intent(v.getContext(),MainActivity.class);
startActivity(i);
getActivity().finish();
}
});
System.out.println("fetch" + sm.fetchContacts());
List<String> nume = new ArrayList<String>();
List<ContactData> contactsList = new ArrayList<ContactData>();
for(String contact : SessionManager.getUserObj().getContactsInfo())
{
for(int i=0; i< sm.fetchContacts().size(); i=i+2){
if(sm.fetchContacts().get(i+1).equals(contact)){
contactsList.add(new ContactData(sm.fetchContacts().get(i).toString(),sm.fetchContacts().get(i+1).toString(),true));
nume.add(sm.fetchContacts().get(i));
}
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, nume);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int itemPosition = position;
// String itemValue = (String) listView.getItemAtPosition(position);
MessagingFragment cChat = new MessagingFragment();
ViewGroup parentViewGroup = (ViewGroup) view.getParent();
System.out.println("Removed Views? ");
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer,cChat).commit();
// Intent i = new Intent(view.getContext(), MessagingActivity.class);
// startActivity(i);
// Here is the tricky part
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Here we set our custom adapter. Now we have the reference to the activity
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_layout);
sm = new SessionManager(this);
if (SessionManager.getUserObj() == null){
// We are checking to see if the Singleton object is set, if it isn't we must send the user back to login screen.
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
finish();
}
ContactListFragment clist = new ContactListFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, clist).commit();
}
}
and this is the fragment
public class MessagingFragment extends Fragment {
private EditText et ;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
container.removeAllViews();
container.removeAllViewsInLayout();
View v = inflater.inflate(R.layout.messaging_screen,null,true);
et = (EditText) v.findViewById(R.id.etmessage);
v.findViewById(R.id.sendMessageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMessageHistory(et.getText().toString());
et.setText("");
}
});
System.out.println("Init1");
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
et = (EditText) view.findViewById(R.id.etmessage);
view.findViewById(R.id.sendMessageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMessageHistory(et.getText().toString());
et.setText("");
}
});
System.out.println("Init2");
}
public void updateMessageHistory(String newText){
TextView tv = (TextView) getView().findViewById(R.id.messageHistory);
String oldText = tv.getText().toString();
oldText = oldText + "\n" + newText ;
tv.setText(oldText);
}
}
Any help would be appreciated.
Back stack is not turned on for fragments by default. But you can enable it easily. Try in your Activity's onCreate() to replace:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clist)
.commit();
with
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clist)
.addToBackStack(null)
.commit();
More info on Back stack:
http://android-er.blogspot.com/2013/04/allow-navigate-back-through.html

Categories

Resources