Fragment disappearing when coming back from another Fragment - android

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;
}
});

Related

Manual Back Press From FragmentA to Homefragment Did Not Work Android Studio,

I Have one Fragment called LatestFragment Code:
public class LatestFragment extends Fragment {
ArrayList<ItemLatest> mListItem;
public RecyclerView recyclerView;
LatestAdapter adapter;
private ProgressBar progressBar;
private LinearLayout lyt_not_found;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
mListItem = new ArrayList<>();
lyt_not_found = rootView.findViewById(R.id.lyt_not_found);
progressBar = rootView.findViewById(R.id.progressBar);
recyclerView = rootView.findViewById(R.id.vertical_courses_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
recyclerView.setFocusable(false);
recyclerView.setNestedScrollingEnabled(false);
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(new API());
jsObj.addProperty("method_name", "get_latest");
if (JsonUtils.isNetworkAvailable(requireActivity())) {
new getLatest(API.toBase64(jsObj.toString())).execute(Constant.API_URL);
}
setHasOptionsMenu(true);
return rootView;
}
#SuppressLint("StaticFieldLeak")
private class getLatest extends AsyncTask<String, Void, String> {
String base64;
private getLatest(String base64) {
this.base64 = base64;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress(true);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0], base64);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
showProgress(false);
if (null == result || result.length() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.ARRAY_NAME);
JSONObject objJson;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
if(objJson.has("status")){
lyt_not_found.setVisibility(View.VISIBLE);
}else {
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJson.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJson.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJson.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJson.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJson.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJson.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJson.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJson.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeCategoryName(objJson.getString(Constant.LATEST_RECIPE_CAT_NAME));
objItem.setRecipeTotalRate(objJson.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeAvgRate(objJson.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeDirection(objJson.getString(Constant.LATEST_RECIPE_DIRE));
objItem.setRecipeIngredient(objJson.getString(Constant.LATEST_RECIPE_INGREDIENT));
mListItem.add(objItem);
}}
} catch (JSONException e) {
e.printStackTrace();
}
displayData();
}
}
}
private void displayData() {
if (getActivity() != null) {
adapter = new LatestAdapter(getActivity(), mListItem);
recyclerView.setAdapter(adapter);
if (adapter.getItemCount() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
lyt_not_found.setVisibility(View.GONE);
}
}
}
private void showProgress(boolean show) {
if (show) {
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
lyt_not_found.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_main, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
final MenuItem searchMenuItem = menu.findItem(R.id.search);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (!hasFocus) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
And HomeFragment Code:
package com.example.fragment;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mCatView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mCatView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
if (Constant.SAVE_ADS_FULL_ON_OFF.equals("true")) {
Constant.AD_COUNT++;
if (Constant.AD_COUNT == Integer.parseInt(Constant.SAVE_ADS_CLICK)) {
Constant.AD_COUNT = 0;
final InterstitialAd mInterstitial = new InterstitialAd(requireActivity());
mInterstitial.setAdUnitId(Constant.SAVE_ADS_FULL_ID);
AdRequest adRequest;
if (JsonUtils.personalization_ad) {
adRequest = new AdRequest.Builder()
.build();
} else {
Bundle extras = new Bundle();
extras.putString("npa", "1");
adRequest = new AdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class, extras)
.build();
}
mInterstitial.loadAd(adRequest);
mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// TODO Auto-generated method stub
super.onAdLoaded();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
}
public void onAdClosed() {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
#Override
public void onAdFailedToLoad(int errorCode) {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
} else {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
btnCat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(2);
String categoryName = getString(R.string.home_category);
FragmentManager fm = getFragmentManager();
CategoryFragment f1 = new CategoryFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
btnLatest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(1);
String categoryName = getString(R.string.home_latest);
FragmentManager fm = getFragmentManager();
LatestFragment f1 = new LatestFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
btnMost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(3);
String categoryName = getString(R.string.menu_most);
FragmentManager fm = getFragmentManager();
MostViewFragment f1 = new MostViewFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//do something
String st_search = edt_search.getText().toString();
Intent intent = new Intent(getActivity(), SearchActivity.class);
intent.putExtra("search", st_search);
startActivity(intent);
edt_search.getText().clear();
}
return false;
}
});
setHasOptionsMenu(true);
return rootView;
}
#SuppressLint("StaticFieldLeak")
private class Home extends AsyncTask<String, Void, String> {
String base64;
private Home(String base64) {
this.base64 = base64;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
mScrollView.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0], base64);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mProgressBar.setVisibility(View.GONE);
mScrollView.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
showToast(getString(R.string.no_data));
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONObject jsonArray = mainJson.getJSONObject(Constant.ARRAY_NAME);
JSONArray jsonSlider = jsonArray.getJSONArray(Constant.HOME_FEATURED_ARRAY);
JSONObject objJsonSlider;
for (int i = 0; i < jsonSlider.length(); i++) {
objJsonSlider = jsonSlider.getJSONObject(i);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJsonSlider.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeType(objJsonSlider.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipeCategoryName(objJsonSlider.getString(Constant.LATEST_RECIPE_CAT_NAME));
objItem.setRecipeName(objJsonSlider.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeImageBig(objJsonSlider.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeImageSmall(objJsonSlider.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipePlayId(objJsonSlider.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
mSliderList.add(objItem);
}
JSONArray jsonLatest = jsonArray.getJSONArray(Constant.HOME_LATEST_CAT);
JSONObject objJsonCat;
for (int k = 0; k < jsonLatest.length(); k++) {
objJsonCat = jsonLatest.getJSONObject(k);
ItemCategory objItem = new ItemCategory();
objItem.setCategoryId(objJsonCat.getString(Constant.CATEGORY_ID));
objItem.setCategoryName(objJsonCat.getString(Constant.CATEGORY_NAME));
objItem.setCategoryImageBig(objJsonCat.getString(Constant.CATEGORY_IMAGE_BIG));
objItem.setCategoryImageSmall(objJsonCat.getString(Constant.CATEGORY_IMAGE_SMALL));
mCatList.add(objItem);
}
JSONArray jsonPopular = jsonArray.getJSONArray(Constant.HOME_LATEST_ARRAY);
JSONObject objJson;
for (int l = 0; l < jsonPopular.length(); l++) {
objJson = jsonPopular.getJSONObject(l);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJson.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJson.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJson.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJson.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJson.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJson.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJson.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJson.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeAvgRate(objJson.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeTotalRate(objJson.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeCategoryName(objJson.getString(Constant.LATEST_RECIPE_CAT_NAME));
mLatestList.add(objItem);
}
JSONArray jsonPopularMost = jsonArray.getJSONArray(Constant.HOME_MOST_ARRAY);
JSONObject objJsonMost;
for (int l = 0; l < jsonPopularMost.length(); l++) {
objJsonMost = jsonPopularMost.getJSONObject(l);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJsonMost.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJsonMost.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJsonMost.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJsonMost.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJsonMost.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJsonMost.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJsonMost.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJsonMost.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeAvgRate(objJsonMost.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeTotalRate(objJsonMost.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeCategoryName(objJsonMost.getString(Constant.LATEST_RECIPE_CAT_NAME));
mMostList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setResult();
}
}
}
private void setResult() {
if (getActivity() != null) {
mLatestAdapter = new HomeAdapter(getActivity(), mLatestList);
mLatestView.setAdapter(mLatestAdapter);
homeMostAdapter = new HomeMostAdapter(getActivity(), mMostList);
mMostView.setAdapter(homeMostAdapter);
homeCategoryAdapter = new HomeCategoryAdapter(getActivity(), mCatList);
mCatView.setAdapter(homeCategoryAdapter);
if (!mSliderList.isEmpty()) {
mViewPager.setAdapter(mAdapter);
if (mSliderList.size() >= 3) {
mViewPager.setCurrentItem(1);
}
}
}
}
private class CustomViewPagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
private CustomViewPagerAdapter() {
// TODO Auto-generated constructor stub
inflater = requireActivity().getLayoutInflater();
}
#Override
public int getCount() {
return mSliderList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View imageLayout = inflater.inflate(R.layout.row_slider_item, container, false);
assert imageLayout != null;
ImageView image = imageLayout.findViewById(R.id.image);
TextView text = imageLayout.findViewById(R.id.text_title);
TextView text_cat = imageLayout.findViewById(R.id.text_cat_title);
LinearLayout lytParent = imageLayout.findViewById(R.id.rootLayout);
text.setText(mSliderList.get(position).getRecipeName());
text_cat.setText(mSliderList.get(position).getRecipeCategoryName());
Picasso.get().load(mSliderList.get(position).getRecipeImageBig()).into(image);
imageLayout.setTag(EnchantedViewPager.ENCHANTED_VIEWPAGER_POSITION + position);
lytParent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopUpAds.ShowInterstitialAds(getActivity(), mSliderList.get(position).getRecipeId());
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
(container).removeView((View) object);
}
}
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_profile, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
// finish();
return true;
case R.id.menu_profile:
if (MyApp.getIsLogin()) {
Intent intent_edit = new Intent(getActivity(), ProfileEditActivity.class);
startActivity(intent_edit);
} else {
final PrettyDialog dialog = new PrettyDialog(requireActivity());
dialog.setTitle(getString(R.string.dialog_warning))
.setTitleColor(R.color.dialog_text)
.setMessage(getString(R.string.login_require))
.setMessageColor(R.color.dialog_text)
.setAnimationEnabled(false)
.setIcon(R.drawable.pdlg_icon_close, R.color.dialog_color, new PrettyDialogCallback() {
#Override
public void onClick() {
dialog.dismiss();
}
})
.addButton(getString(R.string.dialog_ok), R.color.dialog_white_text, R.color.dialog_color, new PrettyDialogCallback() {
#Override
public void onClick() {
dialog.dismiss();
Intent intent_login = new Intent(getActivity(), SignInActivity.class);
intent_login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent_login);
}
})
.addButton(getString(R.string.dialog_no), R.color.dialog_white_text, R.color.dialog_color, new PrettyDialogCallback() {
#Override
public void onClick() {
dialog.dismiss();
}
});
dialog.setCancelable(false);
dialog.show();
}
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
}
When It load LatestFragment and I press back in android device the app Exit,
how to backpress from LatestFragment to HomeFragment
Thanks
Is there a way in which we can implement onBackPressed() in Android Fragment similar to the way in which we implement in Android Activity?
As the Fragment lifecycle do not have onBackPressed(). Is there any other alternative method to over ride onBackPressed() in Android 3.5 fragments?
PLease change in HomeFragment
ft.replace(R.id.fragment1, f1, categoryName); to
ft.add(R.id.fragment1, f1, categoryName);
It adds LatestFragment in stack so when you will press back button from LatestFragment it shows HomeFragment because HomeFragment is still in stack

all Fragment recreating when a switching through fragments using tablayout

I am creating an application which is based on Tabs using tablayout. I didn't use viewpager. My logic is that users can create fragments (Tabs) like adding tabs in chrome so that whenever user clicks add button a new tab is created with a fragment. Now i need to save unique time stamp of each fragment created time in shared preference so that whenever i move to one fragment i can use that shared reference timestamp value to do unique function intended for that particular fragment.
But i don't know where to save that timestamp. I tried to get the time in milliseconds in Oncreate function of Fragment but whenever I switch between tabs everytime the onCreate call so that each time i switch between tabs the shared preference value changes as i added it in onCreate in Fragments.
My Logic is that it should only create once a fragment is created when user clicks add and must be able to use that in fragments.
As every time i switch to other fragement it just reinitilize all view and onCreate in called. so i could not set timestamp in oncreate..
Please help me
my Activity code is:
public class TabActivity extends AppCompatActivity{
public static TabActivity instance;
private FragmentChild fragmentOne;
private TabLayout allTabs;
ImageView add;
ImageView imageButtonAdd2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_activity);
getAllWidgets();
bindWidgetsWithAnEvent();
setupTabLayout();
}
public static TabActivity getInstance() {
return instance;
}
private void getAllWidgets() {
allTabs = (TabLayout) findViewById(R.id.simpleTabLayout);
add = findViewById(R.id.addButton);
imageButtonAdd2 = findViewById(R.id.imageButtonAdd2);
}
private void setupTabLayout() {
allTabs.addTab(allTabs.newTab().setText("ONE"),true);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
allTabs.addTab(allTabs.newTab().setText("NEW_TAB"),true);
bindWidgetsWithAnEvent();
}
});
imageButtonAdd2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(0));
fragmentSecond = new SecondFragment();
fragmentSecond.setArguments(bundle);
replaceFragment(fragmentSecond,"SecondFragment");*/
}
});
}
private void bindWidgetsWithAnEvent()
{
allTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
setCurrentTabFragment(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setCurrentTabFragment(int tabPosition)
{
Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(tabPosition));
fragmentOne = new FragmentChild();
fragmentOne.setArguments(bundle);
replaceFragment(fragmentOne,"FirstFragment");
}
public void replaceFragment(Fragment fragment, String fragmentName) {
long time= System.currentTimeMillis();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment,fragmentName);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
public void backStackFragment(Fragment fragment, String fragmentName) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment,fragmentName);
ft.addToBackStack(null);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
}
FragmentChild class:
public class FragmentChild extends Fragment {
String childname;
TextView textViewChildName;
EditText editText;
private GridView mGridView;
private ListItem mListItem;
private ListView mListview;
private ProgressBar mProgressBar;
private ProductViewAdapter mGridAdapter;
private ListViewAdapter mListAdapter = null;
private ArrayList<GridItem> mGridData;
private ArrayList<ListItem> mListData = null;
ListView listView;
CheckInterNetConnection check ;
Boolean isInternetPresent = false;
PreferenceHelper prefs;
private TabLayout tabLayout;
private ViewPagerAdapter adapter;
public static ViewPager viewPager;
String posid = "";
int page =0;
String title = "";
TabLayout allTabs;
int tab_position = 0;
long time=0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//GlobalBus.getBus().register(this);
View view = inflater.inflate(R.layout.fragment_child, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
Log.e("onCreateView","onCreateView");
getIDs(view);
setEvents();
return view;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
time= System.currentTimeMillis();
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
Log.e("onCreate","onCreate");
}
private void getIDs(View view) {
//textViewChildName = (TextView) view.findViewById(R.id.textViewChild);
//textViewChildName.setText(childname);
//editText = (EditText) view.findViewById(R.id.editText);
//editText.setText("");
}
private void setEvents() {
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.e("onViewCreated","onViewCreated");
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Unregister the registered event.
EventBus.getDefault().unregister(this);
}
public static FragmentChild newInstance(int page, String title) {
FragmentChild fragmentFirst = new FragmentChild();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("onActivityCreated","onActivityCreated");
allTabs = (TabLayout) getActivity().findViewById(R.id.simpleTabLayout);
mGridView = (GridView) getView().findViewById(R.id.gridView);
prefs = new PreferenceHelper(getActivity());
mGridData = new ArrayList<>();
mGridAdapter = new ProductViewAdapter(getActivity(), R.layout.grid_product_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
mListview = (ListView) getView().findViewById(R.id.list);
mListData = new ArrayList<>();
mListAdapter = new ListViewAdapter(getActivity(), R.layout.list_row, mListData);
mListview.setAdapter(mListAdapter);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
}
#Override
public void onStart() {
super.onStart();
Log.e("onStart","onStart");
EventBus.getDefault().register(this);
tab_position=allTabs.getSelectedTabPosition();
//Log.e("TAB ID",String.valueOf(tab_position));
prefs.save(String.valueOf(tab_position),"tab-"+time);
check = new CheckInterNetConnection(getActivity());
isInternetPresent = check.isConnectingToInternet();
if (isInternetPresent) {
fetchProducts(tab_position);
}
}
#Override
public void onResume() {
super.onResume();
Log.e("onResume","onResume");
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
Log.e("onPause","onPause");
super.onPause();
}
#Subscribe
public void onEvent(GlobalBus event){
posid = event.getMessage();
//Toast.makeText(getActivity(), event.getMessage(), Toast.LENGTH_SHORT).show();
}
public void fetchProducts(int tabPosition){
String tabid = prefs.getString(String.valueOf(tabPosition),"0");
Fragment fragment = getFragmentManager().findFragmentById(R.id.simpleFrameLayout);
String tag = (String) fragment.getTag();
//Log.e("URL","http://35.184.41.163/phpmyadmin/app/demo/products.php?tabid="+tabid+"&tab_position="+tabPosition);
RestClientHelper.getInstance().get("http://35.184.41.163/phpmyadmin/app/demo/products.php", new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
parseResult(response);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
try {
ListItem items;
GridItem item = (GridItem) parent.getItemAtPosition(position);
items = new ListItem();
items.setName(item.getTitle());
items.setType(item.getDescription());
mListData.add(items);
}
catch(Exception e){
}
finally {
mListAdapter.setGridData(mListData);
}
}
});
}
#Override
public void onError(String error) {
}
});
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("products");
GridItem item;
if(posts.length() <= 0){
RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
ly.setVisibility(View.VISIBLE);
}
else {
// RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
//ly.setVisibility(View.INVISIBLE);
mGridData.clear();
mGridAdapter.setGridData(mGridData);
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String title = post.optString("name");
String description = post.optString("description");
String image = post.optString("image");
String qty = post.optString("qty");
String quantityin = post.optString("quantityin");
String price = post.optString("price");
item = new GridItem();
item.setId(id);
item.setTitle(title);
item.setDescription(description);
item.setImage(image);
item.setQuantity(qty);
item.setQuantityIn(quantityin);
item.setUnitprice(price);
mGridData.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
finally {
mGridAdapter.setGridData(mGridData);
}
}
}
UPDATE as suggested by #Larry Hsiao
public class TabActivity extends AppCompatActivity{
public static TabActivity instance;
private FragmentChild fragmentOne;
PreferenceHelper prefs;
private TabLayout allTabs;
ImageView add;
ImageView imageButtonAdd2;
private final List<Fragment> fragments = new ArrayList<>(); // maintain the instance for switching
private int currentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_activity);
prefs = new PreferenceHelper(TabActivity.this);
getAllWidgets();
//bindWidgetsWithAnEvent();
setupTabLayout();
bindWidgetsWithAnEvent();
}
public static TabActivity getInstance() {
return instance;
}
private void getAllWidgets() {
allTabs = (TabLayout) findViewById(R.id.simpleTabLayout);
add = findViewById(R.id.addButton);
add.performClick();
imageButtonAdd2 = findViewById(R.id.imageButtonAdd2);
}
private void setupTabLayout() {
int locfirst = allTabs.getSelectedTabPosition();
locfirst = locfirst+1;
allTabs.addTab(allTabs.newTab().setText("TAB"+locfirst),true);
/*long time= System.currentTimeMillis();
prefs.save("tab_"+locfirst,"tab_"+time);*/
fragments.add(newFragment(0));
addFragment(fragments.get(0));
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int loc = allTabs.getSelectedTabPosition();
loc = loc+1;
allTabs.addTab(allTabs.newTab().setText("TAB"+loc),true);
fragments.add(newFragment(loc));
addFragment(fragments.get(loc));
/*bindWidgetsWithAnEvent();
long time= System.currentTimeMillis();
prefs.save("tab_"+loc,"tab_"+time);*/
}
});
imageButtonAdd2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(0));
fragmentSecond = new SecondFragment();
fragmentSecond.setArguments(bundle);
replaceFragment(fragmentSecond,"SecondFragment");*/
}
});
}
private Fragment newFragment(int position) {
Fragment fragment = new FragmentChild();
Bundle bundle = new Bundle();
bundle.putString("position", String.valueOf(position));
fragment.setArguments(bundle);
return fragment;
}
private void addFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.simpleFrameLayout, fragment);
transaction.commit();
}
private void changingTab(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.hide(fragments.get(currentIndex));
if (manager.getFragments().contains(fragment)) {
transaction.show(fragment);
}else {
transaction.add(R.id.simpleFrameLayout,fragment);
}
transaction.commit();
}
private void bindWidgetsWithAnEvent()
{
allTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int nextPageIndex = (currentIndex + 1) % 2; // only two fragment switching
changingTab(fragments.get(nextPageIndex));
currentIndex = nextPageIndex;
//setCurrentTabFragment(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
\
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
}
This force closes with this error:
FATAL EXCEPTION: main
Process: com.eazypos.app, PID: 13624
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.eazypos.app.TabActivity$3.onTabSelected(TabActivity.java:115)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:483)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:465)
at com.eazypos.app.TabActivity$1.onClick(TabActivity.java:62)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
REMOVE TAB FUNCTION
public void removeTab(int position) {
Toast.makeText(getActivity(), "REMOVING --> "+position, Toast.LENGTH_SHORT).show();
prefs.remove("tab_"+position);
if (allTabs.getChildCount() > 0) {
allTabs.removeTabAt(position);
}
}
To save the value only once.. in timeStamp in the shared prefs just use this in each fragment..
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getActivity() == null)
{
// generate time stamp in miliseconds as you are doing
// and save it in shared prefs
// this will be called only once..
}
}
OR YOU CAN TRY IN :-
UPDATE onCreate of fragmentChild
time= System.currentTimeMillis();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("My_prefs_name",Context.MODE_PRIVATE);
String timeStamp = sharedPreferences.getString("timeStamp","");
if ( timeStamp.isEmpty())
{
// SAVE TIME IN SHAREPREFS
sharedPreferences.edit().putString("timeStamp",time).apply();
}
You should maintain the Fragment instance which you already create. (With FragmentManager or just keep it with variable might do the job)
The method setCurrentTabFragment() in Activity which creating new Fragment is invoked every time user click tab. As the result, fragment always run through the onCreate()
// this method invoke every time user click the tab
private void setCurrentTabFragment(int tabPosition){
Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(tabPosition));
fragmentOne = new FragmentChild(); // creating new Fragment
fragmentOne.setArguments(bundle);
replaceFragment(fragmentOne,"FirstFragment");
}
Edited:
Use List to maintain the Fragment instance we already create.
Switch Fragment with hide()/show() provided by FragmentManager, using add() if the Fragment not added to FragmentManager before.
Sample Code:
public class MainActivity extends AppCompatActivity {
private final List<Fragment> fragments = new ArrayList<>();
private int currentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabLayout tabLayout = findViewById(R.id.tabLayout);
// initial with one page
Fragment firstFragment = newFragment(0);
fragments.add(firstFragment);
addFragment(firstFragment);
tabLayout.addTab(tabLayout.newTab().setText("Initial tab"));
// user events
findViewById(R.id.main_createTab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragments.add(newFragment(tabLayout.getTabCount()));
tabLayout.addTab(tabLayout.newTab().setText("Pages " + tabLayout.getTabCount()));
}
});
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int nextPageIndex = tab.getPosition();
if (currentIndex == nextPageIndex){
return;
}
changingTab(fragments.get(nextPageIndex));
currentIndex = nextPageIndex;
}
#Override public void onTabUnselected(TabLayout.Tab tab) {}
#Override public void onTabReselected(TabLayout.Tab tab) {}
});
}
private Fragment newFragment(int position) {
Fragment fragment = new FragmentWithLog();
Bundle bundle = new Bundle();
bundle.putString("position", String.valueOf(position));
fragment.setArguments(bundle);
return fragment;
}
private void addFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.main_fragmentFrame, fragment);
transaction.commit();
}
private void changingTab(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.hide(fragments.get(currentIndex));
if (manager.getFragments().contains(fragment)) {
transaction.show(fragment);
} else {
transaction.add(R.id.main_fragmentFrame, fragment);
}
transaction.commit();
}
}

RecyclerView in fragment through activity get position

so here is my problem, i have only one activity from i launch my viewpager fragment, in my viewpager i have 4 fragments containing recyclerViews. Every Fragment contains item populated by data on the net, when i click into one i get a WebView Fragment, but when i click on the backbutton i lost my poisiton, cause it's recreating the whole activity.
I don't know how to not recreate the activity and get back my old position, or recreating it but not changing the item's positions and have my old position back. Here's my code. Where i should put what ?! Some help would be very very well come.
Thank You !!
My Activity Class :
public class LauncherActivity extends AppCompatActivity implements ListFragment.OnNewSelectedInterface{
public static final String VIEWPAGER_FRAGMENT = "view_pager";
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_launcher);
mImageView = (ImageView) findViewById(R.id.logoImageView);
mImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely));
if(!isNetworkAvailable()){
alertUserAboutError();
} else {
relativeLayout.postDelayed(new Runnable() {
#Override
public void run() {
ViewPagerFragment savedFragment = (ViewPagerFragment)
getSupportFragmentManager().findFragmentByTag(VIEWPAGER_FRAGMENT);
if(savedFragment == null) {
ViewPagerFragment viewPagerFragment = new ViewPagerFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.activity_launcher, viewPagerFragment, VIEWPAGER_FRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}, 2000);
}
}
#Override
public void onListNewSelected(int index, ArrayList<Articles> articles) {
WebViewFragment webViewFragment = new WebViewFragment();
Bundle bundle = new Bundle();
bundle.putInt(ViewPagerFragment.KEY_NEW_INDEX, index);
bundle.putParcelableArrayList(ListFragment.KEY_LIST, articles);
webViewFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getFragmentManager(), "error_dialog");
}
}
My ViewPagerClass :
public class ViewPagerFragment extends Fragment {
public static final String KEY_NEW_INDEX = "key_new_index";
private ViewPager mViewPager;
private TabLayout mTabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
final OldFactFragment oldFactFragment = new OldFactFragment();
final SportFragment sportFragment = new SportFragment();
final BuzzFragment buzzFragment = new BuzzFragment();
final NewsFragment newsFragment = new NewsFragment();
mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
mTabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
if(position == 0){
return oldFactFragment;
} else if (position == 1) {
return newsFragment;
} else if (position == 2){
return sportFragment;
} else return buzzFragment;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Pastly";
} else if (position == 1) {
return "politic";
} else if (position == 2){
return "sport";
} else return "buzz";
}
#Override
public int getCount() {
return 4;
}
});
mTabLayout.setupWithViewPager(mViewPager);
return view;
}
}
My ListFragment(Parent's class of the 4 Fragments in the ViewPager) :
public abstract class ListFragment extends Fragment {
public static final String KEY_LIST = "key_list";
public interface OnNewSelectedInterface {
void onListNewSelected(int index, ArrayList<Articles> articles);
}
protected static final String TAG = ListFragment.class.getSimpleName();
protected ArrayList<Articles> mArticlesList;
protected ItemAdapter mArticleAdapter;
protected RecyclerView mRecyclerView;
protected OnNewSelectedInterface mListener;
protected RecyclerView.LayoutManager mManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mListener = (OnNewSelectedInterface) getActivity();
View view = inflater.inflate(R.layout.fragment_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
getInfos(getUrl());
return view;
}
protected abstract String[] getUrl();
private void getInfos(String[] url) {
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
for (int i = 0; i < getUrl().length; i++) {
Request request = new Request.Builder().url(url[i]).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
Log.v(TAG, jsonData);
getMultipleUrls(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getCurrentArticles(mArticlesList);
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
alertUserAboutError();
}
});
}
});
}
} else{
alertUserAboutError();
}
}
private void getMultipleUrls(String jsonData) throws JSONException {
if (mArticlesList == null) {
mArticlesList = getArticleForecast(jsonData);
} else {
mArticlesList.addAll(getArticleForecast(jsonData));
}
}
private void getCurrentArticles(ArrayList<Articles> articles) {
mArticleAdapter = new ItemAdapter(getActivity(), articles, mListener);
mRecyclerView.setAdapter(mArticleAdapter);
mManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mManager);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getActivity().getFragmentManager(), "error_dialog");
}
private ArrayList<Articles> getArticleForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
JSONArray articles = forecast.getJSONArray("articles");
ArrayList<Articles> listArticles = new ArrayList<>(articles.length());
for (int i = 0; i < articles.length(); i++) {
JSONObject jsonArticle = articles.getJSONObject(i);
Articles article = new Articles();
String urlImage = jsonArticle.getString("urlToImage");
article.setTitle(jsonArticle.getString("title"));
article.setDescription(jsonArticle.getString("description"));
article.setImageView(urlImage);
article.setArticleUrl(jsonArticle.getString("url"));
listArticles.add(i, article);
}
return listArticles;
}
}
And my ItemAdapter (Adapter Class) :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ArticleViewHolder> {
private final ListFragment.OnNewSelectedInterface mListener;
protected ArrayList<Articles> mArticlesList;
protected Context mContext;
private int mPosition;
private int lastPosition = -1;
public ItemAdapter(Context contexts, ArrayList<Articles> mArticleLi, ListFragment.OnNewSelectedInterface listener){
mContext = contexts;
mArticlesList = mArticleLi;
mListener = listener;
}
#Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_linear, parent, false);
view.findViewById(R.id.textView).setSelected(true);
ArticleViewHolder articleViewHolder = new ArticleViewHolder(view);
articleViewHolder.setIsRecyclable(false);
return articleViewHolder;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(ArticleViewHolder holder, int position) {
mPosition = position;
holder.bindArticle(mArticlesList.get(position));
setAnimation(holder.itemView, position);
holder.mImageView.setClipToOutline(true);
}
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(viewToAnimate.getContext(), android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return mArticlesList.size();
}
public class ArticleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
private TextView mTitle, mArticle;
private ImageView mImageView;
private ArticleViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.textView);
mArticle = (TextView) itemView.findViewById(R.id.showTextView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView2);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
private void bindArticle(Articles article) {
mTitle.setText(article.getTitle());
mArticle.setText(article.getDescription());
mArticle.setVisibility(View.INVISIBLE);
Glide.with(mContext).load(article.getImageView()).into(mImageView);
}
#Override
public void onClick(View view) {
mListener.onListNewSelected(getLayoutPosition(), mArticlesList);
}
#Override
public boolean onLongClick(View view) {
String desc = mArticlesList.get(getAdapterPosition()).getDescription();
mArticle.setVisibility(View.VISIBLE);
mArticle.setText(desc);
mArticle.postDelayed(new Runnable() {
public void run() {
mArticle.setVisibility(View.INVISIBLE);
}
}, 3000);
return true;
}
}
}
In Your method onListNewSelected You are Replacing the new fragment with the old one as stated in this line
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
From Google Documentaion
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
So you are removing the old Fragment then adding the new one, When you are back to get the old fragment, It is not already there it will be created from scratch, So the position is already gone with the removed fragment.
While using the add method, Will add the new fragment above the previous one, when you go back the previous one already there with its state "Position"

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.

Call FragmentActivity from Fragment

Can I call a fragmentactivity from a fragment?
If I can call,how can it be done?
Otherwise, how can I solve this problem ?
In my code, I want to call FragmentWizard.class from the "FragmentMain" fragment,but this doesn't compile.
Below is my code:
public class FragmentMain extends Fragment {
TextView textView;
Button x;
public FragmentMain() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, null);
textView = (TextView) view.findViewById(R.id.fragment_main_textview);
x = (Button) view.findViewById(R.id.deneme);
x.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent firstpage= new Intent(getActivity(),FragmentWizard.class);
startActivity(firstpage);
}
});
return view;
}
}
FragmentWizard.java
public class FragmentWizard extends FragmentActivity implements
PageFragmentCallbacks, ReviewFragment.Callbacks, ModelCallbacks {
private ViewPager mPager;
private MyPagerAdapter mPagerAdapter;
private boolean mEditingAfterReview;
private AbstractWizardModel mWizardModel = new SandwichWizardModel(this);
private boolean mConsumePageSelectedEvent;
private Button mNextButton;
private Button mPrevButton;
private List<Page> mCurrentPageSequence;
private StepPagerStrip mStepPagerStrip;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mWizardModel.load(savedInstanceState.getBundle("model"));
}
mWizardModel.registerListener(this);
mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mPagerAdapter);
mStepPagerStrip = (StepPagerStrip) findViewById(R.id.strip);
mStepPagerStrip
.setOnPageSelectedListener(new StepPagerStrip.OnPageSelectedListener() {
#Override
public void onPageStripSelected(int position) {
position = Math.min(mPagerAdapter.getCount() - 1,
position);
if (mPager.getCurrentItem() != position) {
mPager.setCurrentItem(position);
}
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mPrevButton = (Button) findViewById(R.id.prev_button);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mStepPagerStrip.setCurrentPage(position);
if (mConsumePageSelectedEvent) {
mConsumePageSelectedEvent = false;
return;
}
mEditingAfterReview = false;
updateBottomBar();
}
});
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mPager.getCurrentItem() == mCurrentPageSequence.size()) {
DialogFragment dg = new DialogFragment() {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setMessage(R.string.submit_confirm_message)
.setPositiveButton(
R.string.submit_confirm_button,
null)
.setNegativeButton(android.R.string.cancel,
null).create();
}
};
dg.show(getSupportFragmentManager(), "place_order_dialog");
} else {
if (mEditingAfterReview) {
mPager.setCurrentItem(mPagerAdapter.getCount() - 1);
} else {
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
}
}
}
});
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
});
onPageTreeChanged();
updateBottomBar();
}
#Override
public void onPageTreeChanged() {
mCurrentPageSequence = mWizardModel.getCurrentPageSequence();
recalculateCutOffPage();
mStepPagerStrip.setPageCount(mCurrentPageSequence.size() + 1); // + 1 =
// review
// step
mPagerAdapter.notifyDataSetChanged();
updateBottomBar();
}
private void updateBottomBar() {
int position = mPager.getCurrentItem();
if (position == mCurrentPageSequence.size()) {
mNextButton.setText(R.string.finish);
mNextButton.setBackgroundResource(R.drawable.finish_background);
mNextButton.setTextAppearance(this, R.style.TextAppearanceFinish);
} else {
mNextButton.setText(mEditingAfterReview ? R.string.review
: R.string.next);
mNextButton
.setBackgroundResource(R.drawable.selectable_item_background);
TypedValue v = new TypedValue();
getTheme().resolveAttribute(android.R.attr.textAppearanceMedium, v,
true);
mNextButton.setTextAppearance(this, v.resourceId);
mNextButton.setEnabled(position != mPagerAdapter.getCutOffPage());
}
mPrevButton
.setVisibility(position <= 0 ? View.INVISIBLE : View.VISIBLE);
}
#Override
protected void onDestroy() {
super.onDestroy();
mWizardModel.unregisterListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle("model", mWizardModel.save());
}
#Override
public AbstractWizardModel onGetModel() {
return mWizardModel;
}
......
}
}
use getActivity() method. Which will return the enclosing activity for the fragment.
Intent firstpage= new Intent(getActivity(),FragmentWizard.class);
getActivity().startActivity(firstpage); // You same startActivity method in fragment as well you can use any of this
public final Activity getActivity ()
You have to use onActivityCreated method to use that:
In your class, just do:
public class FragmentMain extends Fragment {
public FragmentMain() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main,container, false);
return view;
}
}
And immediately after that, use the onActivityCreated method:
Here's the code:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView textView = (TextView) getActivity().findViewById(R.id.fragment_main_textview);
Button x = (Button) getActivity().findViewById(R.id.deneme);
x.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent firstpage= new Intent(getActivity(),FragmentWizard.class);
getActivity().startActivity(firstpage);
}
});
}
Hope this works..:)

Categories

Resources