I have a Fragment class and an Activity class which is related to that fragment, ViewPager has been initialized inside the Activity of MizActivity
My question is it possible to move ViewPager initialization from Activity class to the Fragment class So that I have better control?
Thanks in advance
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
TextClicked mCallback;
public interface TextClicked{
void sendText(int position);
}
private Activity mContext;
private TvShowEpisode mEpisode;
private ImageView mBackdrop, mEpisodePhoto;
private TextView mTitle, mDescription, mFileSource, mAirDate, mRating, mDirector, mWriter, mGuestStars, mSeasonEpisodeNumber;
private View mDetailsArea;
private Picasso mPicasso;
private Typeface mMediumItalic, mMedium, mCondensedRegular;
private DbAdapterTvShowEpisodes mDatabaseHelper;
private long mVideoPlaybackStarted, mVideoPlaybackEnded;
private boolean mShowFileLocation;
private Bus mBus;
private int mToolbarColor = 0;
private FloatingActionButton mFab;
private PaletteLoader mPaletteLoader;
private ObservableScrollView mScrollView;
private RecyclerView mEpisodesList;
private String mShowId;
private ArrayList<TvShowEpisode> mEpisodes = new ArrayList<TvShowEpisode>();
private static final String SHOW_ID = "showId";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ViewPager mViewPager;
public PlanetAdapter.OnItemClickListener listener;
/**
* Empty constructor as per the Fragment documentation
*/
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
// initializing mEpisodes
mShowId = getActivity().getIntent().getExtras().getString(SHOW_ID);
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(mContext, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
} // mEpisodes initialized
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (TextClicked) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement TextClicked");
}
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
// setting RecyclerView
mEpisodesList = (RecyclerView) view.findViewById(R.id.episodesLIST);
// getting episodeslist
ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
mEpisodesList.setAdapter(new PlanetAdapter(episodeslist, new PlanetAdapter.OnItemClickListener() {
#Override public void onItemClick(String item) {
SharedPreferences getPref = getActivity ().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition",0);
mCallback.sendText(pos);
}
}));
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
if (MizLib.isTablet(mContext))
mFab.setType(FloatingActionButton.TYPE_NORMAL);
final int height = MizLib.getActionBarAndStatusBarHeight(getActivity());
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mScrollView.setOnScrollChangedListener(new OnScrollChangedListener() {
#Override
public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
final int headerHeight = mEpisodePhoto.getHeight() - height;
final float ratio = (float) Math.min(Math.max(t, 0), headerHeight) / headerHeight;
final int newAlpha = (int) (ratio * 255);
mBus.post(new BusToolbarColorObject(mToolbarColor, newAlpha));
if (MizLib.isPortrait(mContext)) {
// Such parallax, much wow
mEpisodePhoto.setPadding(0, (int) (t / 1.5), 0, 0);
}
}
});
mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewUtils.setLayoutParamsForDetailsEmptyView(mContext, view,
mBackdrop, mScrollView, this);
}
});
loadData();
mPicasso.load(mEpisode.getEpisodePhoto()).placeholder(R.drawable.bg).config(MizuuApplication.getBitmapConfig()).into(mEpisodePhoto, new Callback() {
#Override
public void onError() {
if (!isAdded())
return;
int width = getActivity().getResources().getDimensionPixelSize(R.dimen.episode_details_background_overlay_width);
int height = getActivity().getResources().getDimensionPixelSize(R.dimen.episode_details_background_overlay_height);
mPicasso.load(mEpisode.getTvShowBackdrop()).placeholder(R.drawable.bg).error(R.drawable.nobackdrop).resize(width, height).config(MizuuApplication.getBitmapConfig()).into(mEpisodePhoto);
}
#Override
public void onSuccess() {
if (mPaletteLoader == null) {
mPaletteLoader = new PaletteLoader(mPicasso, Uri.fromFile(mEpisode.getEpisodePhoto()), new PaletteLoader.OnPaletteLoadedCallback() {
#Override
public void onPaletteLoaded(int swatchColor) {
mToolbarColor = swatchColor;
}
});
mPaletteLoader.addView(mDetailsArea);
mPaletteLoader.setFab(mFab);
mPaletteLoader.execute();
} else {
// Clear old views after configuration change
mPaletteLoader.clearViews();
// Add views after configuration change
mPaletteLoader.addView(mDetailsArea);
mPaletteLoader.setFab(mFab);
// Re-color the views
mPaletteLoader.colorViews();
}
}
});
if (!MizLib.isPortrait(getActivity()))
mPicasso.load(mEpisode.getEpisodePhoto()).placeholder(R.drawable.bg).error(R.drawable.bg).transform(new BlurTransformation(getActivity().getApplicationContext(), mEpisode.getEpisodePhoto().getAbsolutePath() + "-blur", 4)).into(mBackdrop, new Callback() {
#Override public void onError() {
if (!isAdded())
return;
mPicasso.load(mEpisode.getTvShowBackdrop()).placeholder(R.drawable.bg).error(R.drawable.nobackdrop).transform(new BlurTransformation(getActivity().getApplicationContext(), mEpisode.getTvShowBackdrop().getAbsolutePath() + "-blur", 4)).into(mBackdrop, new Callback() {
#Override
public void onError() {}
#Override
public void onSuccess() {
if (!isAdded())
return;
mBackdrop.setColorFilter(Color.parseColor("#aa181818"), android.graphics.PorterDuff.Mode.SRC_OVER);
}
});
}
#Override
public void onSuccess() {
if (!isAdded())
return;
mBackdrop.setColorFilter(Color.parseColor("#aa181818"), android.graphics.PorterDuff.Mode.SRC_OVER);
}
});
}
#Override
public void onDetach() {
mCallback = null; // => avoid leaking, thanks #Deepscorn
super.onDetach();
}
private void loadData() {
// Set the episode title
mTitle.setVisibility(View.VISIBLE);
mTitle.setText(mEpisode.getTitle());
mTitle.setTypeface(mCondensedRegular);
mDescription.setTypeface(mCondensedRegular);
mFileSource.setTypeface(mCondensedRegular);
mDirector.setTypeface(mCondensedRegular);
mWriter.setTypeface(mCondensedRegular);
mGuestStars.setTypeface(mCondensedRegular);
mAirDate.setTypeface(mMedium);
mRating.setTypeface(mMedium);
mSeasonEpisodeNumber.setTypeface(mMediumItalic);
mSeasonEpisodeNumber.setText(getString(R.string.showSeason) + " " + mEpisode.getSeason() + ", " + getString(R.string.showEpisode) + " " + mEpisode.getEpisode());
// Set the movie plot
if (!MizLib.isPortrait(getActivity())) {
mDescription.setBackgroundResource(R.drawable.selectable_background);
mDescription.setMaxLines(getActivity().getResources().getInteger(R.integer.episode_details_max_lines));
mDescription.setTag(true); // true = collapsed
mDescription.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((Boolean) mDescription.getTag())) {
mDescription.setMaxLines(1000);
mDescription.setTag(false);
} else {
mDescription.setMaxLines(getActivity().getResources().getInteger(R.integer.episode_details_max_lines));
mDescription.setTag(true);
}
}
});
mDescription.setEllipsize(TextUtils.TruncateAt.END);
mDescription.setFocusable(true);
} else {
if (MizLib.isTablet(getActivity()))
mDescription.setLineSpacing(0, 1.15f);
}
mDescription.setText(mEpisode.getDescription());
if (mShowFileLocation) {
mFileSource.setText(mEpisode.getAllFilepaths());
} else {
mFileSource.setVisibility(View.GONE);
}
// Set the episode air date
mAirDate.setText(MizLib.getPrettyDatePrecise(getActivity(), mEpisode.getReleasedate()));
// Set the movie rating
if (!mEpisode.getRating().equals("0.0")) {
try {
int rating = (int) (Double.parseDouble(mEpisode.getRating()) * 10);
mRating.setText(Html.fromHtml(rating + "<small> %</small>"));
} catch (NumberFormatException e) {
mRating.setText(mEpisode.getRating());
}
} else {
mRating.setText(R.string.stringNA);
}
if (TextUtils.isEmpty(mEpisode.getDirector()) || mEpisode.getDirector().equals(getString(R.string.stringNA))) {
mDirector.setVisibility(View.GONE);
} else {
mDirector.setText(mEpisode.getDirector());
}
if (TextUtils.isEmpty(mEpisode.getWriter()) || mEpisode.getWriter().equals(getString(R.string.stringNA))) {
mWriter.setVisibility(View.GONE);
} else {
mWriter.setText(mEpisode.getWriter());
}
if (TextUtils.isEmpty(mEpisode.getGuestStars()) || mEpisode.getGuestStars().equals(getString(R.string.stringNA))) {
mGuestStars.setVisibility(View.GONE);
} else {
mGuestStars.setText(mEpisode.getGuestStars());
}
}
Rest of the code
}
Activity
public class TvShowEpisodeDetails extends MizActivity implements TvShowEpisodeDetailsFragment.TextClicked{
private static final String SHOW_ID = "showId";
private ArrayList<TvShowEpisode> mEpisodes = new ArrayList<TvShowEpisode>();
private int mSeason, mEpisode;
private String mShowId, mShowTitle;
private ViewPager mViewPager;
private DbAdapterTvShowEpisodes mDatabaseHelper;
private Bus mBus;
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
ViewUtils.setupWindowFlagsForStatusbarOverlay(getWindow(), true);
ViewUtils.setProperToolbarSize(this, mToolbar);
mShowId = getIntent().getExtras().getString(SHOW_ID);
mSeason = getIntent().getExtras().getInt("season");
mEpisode = getIntent().getExtras().getInt("episode");
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(this, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
}
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
mShowTitle = MizuuApplication.getTvDbAdapter().getShowTitle(mShowId);
setTitle(mShowTitle);
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
//notify your recycler views adaper
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
SharedPreferences setPref = this.getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
setPref.edit().putInt("i", i).apply();
break;
}
}
}
}
#Subscribe
public void onScrollChanged(TvShowEpisodeDetailsFragment.BusToolbarColorObject object) {
ViewUtils.updateToolbarBackground(this, mToolbar, object.getAlpha(),
mEpisodes.get(mViewPager.getCurrentItem()).getTitle(), object.getToolbarColor());
}
public void onResume() {
super.onResume();
mBus.register(this);
ViewUtils.updateToolbarBackground(this, mToolbar, 0, mShowTitle, Color.TRANSPARENT);
}
#Override
public void onPause() {
super.onPause();
mBus.unregister(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onStart() {
super.onStart();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", mViewPager.getCurrentItem());
}
#Override
public void sendText(int position) {
mViewPager.setCurrentItem(position,false);
//Toast.makeText(getContext(), "Item Clicked " + text, Toast.LENGTH_SHORT).show();
}
private class TvShowEpisodeDetailsAdapter extends FragmentPagerAdapter {
public TvShowEpisodeDetailsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return TvShowEpisodeDetailsFragment.newInstance(mShowId, Integer.parseInt(mEpisodes.get(index).getSeason()), Integer.parseInt(mEpisodes.get(index).getEpisode()));
}
#Override
public int getCount() {
return mEpisodes.size();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
setResult(Activity.RESULT_OK);
finish();
}
}
}
}
Yes, a Viewpager can be setup in a Fragment.
You just need to get the right FragmentManager when constructing it i.e use getChildFragmentManager() in mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
From https://developer.android.com/guide/fragments/fragmentmanager
Access the FragmentManager
Accessing in an activity
Every FragmentActivity and subclasses thereof, such as
AppCompatActivity, have access to the FragmentManager through the
getSupportFragmentManager() method.
Accessing in a Fragment
Fragments are also capable of hosting one or more child fragments.
Inside a fragment, you can get a reference to the FragmentManager that
manages the fragment's children through getChildFragmentManager().
Related
I initialy had Radio player i.e RadioActivity, which was working perfectly
The problem
I later decided to have a dashboad as the main activity where you can click a button to take you to the RadioActivty. Now app keeps crashing after splashscreen
Find The Codes Below
SplashScreen
private static int SPLASH_TIMER = 8000;
ImageView backgroundImage;
ImageView theLogo;
TextView poweredByLine;
Animation sideAnim, bottomAnim;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
getWindow().setFlags(WindowManager.LayoutParams.FLAGS_CHANGED,WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
setContentView(R.layout.activity_splash_screen);
backgroundImage = findViewById(R.id.background_image);
theLogo = findViewById(R.id.the_Logo);
poweredByLine = findViewById(R.id.powered_by_line);
sideAnim = AnimationUtils.loadAnimation(this, R.anim.side_anim);
bottomAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_anim);
backgroundImage.setAnimation(sideAnim);
theLogo.setAnimation(sideAnim);
poweredByLine.setAnimation(bottomAnim);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), OnBoarding.class);
startActivity(intent);
finish();
}
},SPLASH_TIMER);
}
}
OnBoarding
CardView nextCard;
LinearLayout dotsLayout;
ViewPager viewPager;
TextView[] dots;
int currentPosition;
SaveState saveState ;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);
nextCard = findViewById(R.id.nextCard);
dotsLayout = findViewById(R.id.dotsLayout);
viewPager = findViewById(R.id.slider);
dotsFunction(0);
saveState = new SaveState(OnBoarding.this,"OB");
if (saveState.getState() == 1){
Intent i = new Intent(OnBoarding.this,DashboardActivity.class);
startActivity(i);
finish();
}
OnBoardingAdapter adapter = new OnBoardingAdapter(this);
viewPager.setAdapter(adapter);
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1,true);
}
});
viewPager.setOnPageChangeListener(onPageChangeListener);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void dotsFunction(int pos){
dots = new TextView[4];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length ; i++){
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextColor(getColor(R.color.white)); //this is the non selection color
dots[i].setTextSize(30);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0){
dots[pos].setTextColor(getColor(R.color.teal_700)); //this is the selection color
dots[pos].setTextSize(40); //this is the selection size
}
}
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onPageSelected(int position) {
dotsFunction(position);
currentPosition = position;
if (currentPosition <= 2){
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1);
}
});
}else{
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveState.setState(1);
Intent i = new Intent(OnBoarding.this, DashboardActivity.class);
startActivity(i);
finish();
}
});
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
DashBoardActivity
public class DashboardActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView imageViewWebsite,imageViewEvents,imageViewLive,
imageViewVideos,imageViewBranches,imageViewDonate,
imageViewEkuwe,imageViewRadio,imageViewAudio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//defininf Cards
imageViewWebsite = (ImageView) findViewById(R.id.website_card);
imageViewEvents = (ImageView) findViewById(R.id.event_card);
imageViewLive = (ImageView) findViewById(R.id.live_card);
imageViewVideos = (ImageView) findViewById(R.id.videos_card);
imageViewBranches = (ImageView) findViewById(R.id.branches_card);
imageViewDonate = (ImageView) findViewById(R.id.donate_card);
imageViewEkuwe = (ImageView) findViewById(R.id.ekuwe_card);
imageViewRadio = (ImageView) findViewById(R.id.radio_card);
imageViewAudio = (ImageView) findViewById(R.id.audio_card);
//Add CLick listener to the card
imageViewWebsite.setOnClickListener(this);
imageViewEvents.setOnClickListener(this);
imageViewLive.setOnClickListener(this);
imageViewVideos.setOnClickListener(this);
imageViewBranches.setOnClickListener(this);
imageViewDonate.setOnClickListener(this);
imageViewEkuwe.setOnClickListener(this);
imageViewRadio.setOnClickListener(this);
imageViewAudio.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.website_card : i = new Intent(this, WebsiteActivity.class);startActivity(i); break;
case R.id.event_card : i = new Intent(this,EventsActivity.class);startActivity(i); break;
case R.id.live_card : i = new Intent(this, LiveActivity.class);startActivity(i); break;
case R.id.videos_card : i = new Intent(this, VideoActivity.class);startActivity(i); break;
case R.id.branches_card : i = new Intent(this,BranchesActivity.class);startActivity(i); break;
case R.id.donate_card : i = new Intent(this, DonateActivity.class);startActivity(i); break;
case R.id.ekuwe_card : i = new Intent(this,EkuweActivity.class);startActivity(i); break;
case R.id.radio_card : i = new Intent(this,RadioActivity.class);startActivity(i); break;
case R.id.audio_card : i = new Intent(this,AudioActivity.class);startActivity(i); break;
default:break;
}
}
}
RadioActivity
public class RadioActivity extends AppCompatActivity {
private TextView nowPlaying;
private ImageView playStop;
private BroadcastReceiver broadcastReceiver;
private String nowPlayingData = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
playStop = findViewById(R.id.playStopBtn);
nowPlaying = findViewById(R.id.radioStationNowPlaying);
setIsPlaying(false);
processPhoneListenerPermission();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
if (tm != null) {
if (tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
if (getIsPlaying()) {
stop();
}
System.exit(0);
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
registerReceiver(broadcastReceiver, filter);
loadNowPlaying();
playStop.setOnClickListener(view -> {
if (isNetworkAvailable()) {
if (getIsPlaying()) {
stop();
} else {
play();
}
} else {
Toast.makeText(getApplicationContext(), "No internet", Toast.LENGTH_LONG).show();
}
});
}
private void loadNowPlaying() {
Thread t = new Thread() {
public void run() {
try {
while (!isInterrupted()) {
runOnUiThread(() -> reloadShoutCastInfo());
Thread.sleep(20000);
}
} catch (InterruptedException ignored) {
}
}
};
t.start();
}
private void reloadShoutCastInfo() {
if (isNetworkAvailable()) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
}
#SuppressLint("StaticFieldLeak")
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource(STREAMING_URL);
nowPlayingData = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ICY_METADATA).replaceAll("StreamTitle", "").replaceAll("[=,';]+", "");
mmr.release();
return null;
}
#Override
protected void onPostExecute(String result) {
nowPlaying.setText(nowPlayingData);
}
}
private void processPhoneListenerPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 121);
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (cm != null) {
networkInfo = cm.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 121) {
if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(getApplicationContext(), "Permission not granted.\nWe can't pause music when phone ringing.", Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", (dialog, id) -> {
if (getIsPlaying()) {
stop();
}
System.exit(0);
})
.setNegativeButton("No", (dialog, id) -> dialog.cancel());
AlertDialog alert = builder.create();
alert.show();
}
private void setIsPlaying(boolean status) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE).edit();
editor.putBoolean("isPlaying", status);
editor.apply();
}
private boolean getIsPlaying() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE);
return prefs.getBoolean("isPlaying", false);
}
private void play() {
setIsPlaying(true);
Intent servicePlayIntent = new Intent(this, MyService.class);
servicePlayIntent.putExtra("playStop", "play");
startService(servicePlayIntent);
playStop.setImageResource(R.drawable.ic_pause);
Toast.makeText(getApplicationContext(), "Loading ...", Toast.LENGTH_LONG).show();
}
private void stop() {
setIsPlaying(false);
Intent serviceStopIntent = new Intent(this, MyService.class);
serviceStopIntent.putExtra("playStop", "stop");
startService(serviceStopIntent);
playStop.setImageResource(R.drawable.ic_play);
Toast.makeText(getApplicationContext(), "Stop Radio...", Toast.LENGTH_LONG).show();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
stopService(new Intent(getApplicationContext(), MyService.class));
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
}
OnBoardingAdapter
public class OnBoardingAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
public OnBoardingAdapter(Context context) {
this.context = context;
}
int titles[] = {
R.string.title1,
R.string.title2,
R.string.title3,
R.string.title4
};
int subtitles[] = {
R.string.subtitle1,
R.string.subtitle2,
R.string.subtitle3,
R.string.subtitle4
};
int images[] = {
R.drawable.on_boarding_vector_1,
R.drawable.on_boarding_vector_2,
R.drawable.on_boarding_vector_3,
R.drawable.on_boarding_vector_4
};
int bg[] = {
R.drawable.bg1,
R.drawable.bg2,
R.drawable.bg3,
R.drawable.bg4
};
#Override
public int getCount() {
return titles.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.slide,container,false);
ImageView image = v.findViewById(R.id.slideImg);
TextView title = v.findViewById(R.id.sliderTitle);
TextView subtitle = v.findViewById(R.id.sliderSubtitle);
ConstraintLayout layout = v.findViewById(R.id.sliderLayout);
image.setImageResource(images[position]);
title.setText(titles[position]);
subtitle.setText(subtitles[position]);
layout.setBackgroundResource(bg[position]);
container.addView(v);
return v;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
I found the solution to this, I had to turn to Design Mode and Inspected everything i
found the problem on line 18 DashboardActivity.xml
I changed this
com.google.android.material.bottomappbar.BottomAppBar to
com.google.android.material.appbar.AppBarLayout
Hi I want to save Recylerview scroll position when screen rotates so that Recyclerview scrolls to that position before user sees screen.
I have tried every possible solution so far for similar questions but nothing is working. I am using GridLayoutManager with Recyclerview and displaying grid list of movies using JSON data.
Please have a look!!
MainActivity:
public class MainActivity extends AppCompatActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
private RecyclerView recyclerView;
private ArrayList<Movie> movieList;
MovieAdapter adapter;
private final String KEY_RECYCLER_STATE = "recycler_state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
movieList = new ArrayList<>();
adapter = new MovieAdapter(this, movieList);
/*
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
}
*/
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setAdapter(adapter);
checkSort();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_RECYCLER_STATE, recyclerView.getLayoutManager().onSaveInstanceState());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState != null)
{
Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(KEY_RECYCLER_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);
}
}
public Activity getActivity() {
Context context = this;
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
private void JSONMostPopularMovie() {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(getApplicationContext(), "There Is No API Key!", Toast.LENGTH_SHORT).show();
return;
}
MovieApi movieapi = new MovieApi();
MovieService apiService = MovieApi.getClient().create(MovieService.class);
Call<MovieResponse> call = apiService.getPopularMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
ArrayList<Movie> movies = response.body().getResults();
adapter.setMovies(movies);
Toast.makeText(MainActivity.this, "Displaying By Most Popular Movies", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d("Error", "" + t.getMessage());
Toast.makeText(MainActivity.this, "Error Fetching Data! And Internet Connection", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
private void JSONTopRateMovie() {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(getApplicationContext(), "There Is No API Key", Toast.LENGTH_SHORT).show();
return;
}
MovieApi movieapi = new MovieApi();
MovieService apiService = MovieApi.getClient().create(MovieService.class);
Call<MovieResponse> call = apiService.getTopRatedMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
ArrayList<Movie> movies = response.body().getResults();
adapter.setMovies(movies);
Toast.makeText(MainActivity.this, "Displaying By Top Rated Movies", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d("Error", "" + t.getMessage());
Toast.makeText(MainActivity.this, "Error Fetching Data! And Internet Connection", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent setting = new Intent(this, MovieSettings.class);
startActivity(setting);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
checkSort();
}
private void checkSort() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortOrder = preferences.getString(
this.getString(R.string.pref_sort_order_key),
this.getString(R.string.pref_most_popular)
);
if (sortOrder.equals(this.getString(R.string.pref_most_popular))) {
Log.d(LOG_TAG, "Sorting by most popular");
JSONMostPopularMovie();
} else if (sortOrder.equals(this.getString(R.string.top_rated))) {
Log.d(LOG_TAG, "Sorting by top rated");
JSONTopRateMovie();
}
}
}
Adapter:
public class MovieAdapter extends
RecyclerView.Adapter<MovieAdapter.MyViewHolder> {
private Context mContext;
private ArrayList<Movie> movieList;
public MovieAdapter(Context mContext, ArrayList<Movie> movieList) {
this.mContext = mContext;
this.movieList = movieList;
}
#Override
public MovieAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.movie_item, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MovieAdapter.MyViewHolder viewHolder, int i) {
viewHolder.title.setText(movieList.get(i).getOriginalTitle());
String vote = Double.toString(movieList.get(i).getVoteAverage());
viewHolder.userrating.setText(vote);
String poster = "https://image.tmdb.org/t/p/w185/" + movieList.get(i).getPosterPath();
Picasso.with(mContext)
.load(poster)
.into(viewHolder.thumbnail);
}
#Override
public int getItemCount() {
return movieList.size();
}
public void setMovies(ArrayList<Movie> movies){
this.movieList = movies;
notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, userrating;
public ImageView thumbnail;
public MyViewHolder(final View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
userrating = (TextView) view.findViewById(R.id.userrating);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Intent intent = new Intent(mContext, MovieDetail.class);
intent.putExtra("movie", movieList.get(position));
intent.putExtra("id", movieList.get(position).getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
});
}
}
}
I have an activity which loads a fragment but when I press back button on the fragment it shows the error :-
"java.lang.IllegalStateException: Fragment ProductFragment{c46ba8a} not attached to Activity"
Code is below:-
Product Fragment:
public class ProductFragment extends Fragment implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {
private static final String PRODUCT_DATA = "product_data";
private TabLayout tabLayout;
private ViewPager viewPager;
NestedScrollView nestedScrollView;
//RecyclerView listView;
//ImageView ivHeader;
ProgressDialog pd;
Bundle bundle;
ViewPager viewPager1;
private LinearLayout pager_indicator;
public String DATA = "data";
public String PRODUCTS = "products";
//public String SPRODUCTS = "sproducts";
public String ID = "id";
public String NAME = "productName";
public String IMAGEURL = "productImg1";
public String DESCRIPTION = "description";
public String PRICE = "price";
public String DELIVERYTYPE = "deliverytype";
//String url = "https://chiraggohil.000webhostapp.com/product.php";
String url = "http://www.thinkdream.in/lunchbox2/product_api/getProductList";
String sliderImageUrl = "http://www.thinkdream.in/lunchbox2/assets/images/product/2.png";
ArrayList<Product> list = new ArrayList<>();
ArrayList<Product> sliderImagesList = new ArrayList<>();
private int dotsCount = 0;
private ImageView[] dots;
private static int CURRENT_PAGE = 0;
ViewPagerSliderAdapter viewPagerSliderAdapter;
ConnectivityManager cm;
NetworkInfo activeNetwork;
boolean isConnected;
//private boolean load = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_product, container, false);
viewPager1 = (ViewPager) v.findViewById(R.id.viewpager);
//listView = (RecyclerView) v.findViewById(R.id.gvProducts);
nestedScrollView = (NestedScrollView) v.findViewById(R.id.nestedSV);
pager_indicator = (LinearLayout) v.findViewById(R.id.viewPagerCountDots);
//nestedScrollView.setFillViewport(true);
//ivHeader = (ImageView) v.findViewById(R.id.ivHeader);
bundle = new Bundle();
tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (savedInstanceState != null) {
sliderImagesList = savedInstanceState.getParcelableArrayList(PRODUCT_DATA);
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
} else {
if (isConnected) {
new GetUrlData(getActivity()).execute();
} else {
Toast.makeText(getActivity(), "You are not connected to the internet!", Toast.LENGTH_SHORT).show();
}
}
tabLayout.addTab(tabLayout.newTab().setText("Pizza"));
tabLayout.addTab(tabLayout.newTab().setText("Sandwich"));
tabLayout.addTab(tabLayout.newTab().setText("Burger"));
Pager adapter = new Pager(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(this);
viewPager1.addOnPageChangeListener(this);
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(PRODUCT_DATA, sliderImagesList);
}
#Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
//Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
private class GetUrlData extends AsyncTask<Void, Void, Void> {
GetUrlData(Context context) {
pd = new MyCustomProgressDialog(context, R.style.NewDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.show();
}
#Override
protected Void doInBackground(Void... voids) {
ServiceHandler sh = new ServiceHandler();
String result = sh.Getdata(url);
//list.clear();
sliderImagesList.clear();
if (result != null) {
try {
list.clear();
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(DATA);
//JSONArray jsonArray = jsonObject1.getJSONArray(PRODUCTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
String id = jsonObject2.getString(ID);
String name = jsonObject2.getString(NAME);
String imgpath = jsonObject2.getString(IMAGEURL);
String desc = jsonObject2.getString(DESCRIPTION);
String price = jsonObject2.getString(PRICE);
//String deliverytype = jsonObject2.getString(DELIVERYTYPE);
Product product = new Product();
product.setId(id);
product.setProductName(name);
product.setProductImage(imgpath);
product.setProductDescription(desc);
product.setProductPrice(price);
//list.add(product);
sliderImagesList.add(product);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
pd.dismiss();
// Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
if(isAdded()) {
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
Log.e("slider",sliderImagesList.toString());
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
slider();
setUiPageViewController();
}else {
Log.e("not added","not added");
}
}
}
private void slider() {
int NUM_PAGES = sliderImagesList.size();
final android.os.Handler handler = new android.os.Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
CURRENT_PAGE = viewPager1.getCurrentItem();
if (CURRENT_PAGE == 2) {
CURRENT_PAGE = -1;
}
viewPager1.setCurrentItem(CURRENT_PAGE + 1, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(runnable);
}
}, 100, 4000);
}
private void setUiPageViewController() {
dotsCount = 3;
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
I don't know where I am wrong. I have searched for the error and even tried the solution from the link below:
Fragment MyFragment not attached to Activity
I ask questions on SO but I don't get response/answers. May be there is a small mistake, grammatical/formating problem, or a duplicate question but there is a possibility of my case that is different then others.
So please help and response.
Thanks.
--Edited--
HomeActivity :
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
TextView tvActionTitle;
SessionManager sessionManager;
GPSTracker gps;
int i = 0;
private FrameLayout redCircle;
private TextView countTextView;
int cartcount = 0;
Menu menu;
LunchBoxDB lunchBoxDB;
private String uid;
SharedPreferences pref;
private int totalquantity = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation);
tvActionTitle = (TextView) findViewById(R.id.tvActionTitle);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Quicksand_Bold_Oblique.otf");
tvActionTitle.setTypeface(custom_font);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
lunchBoxDB = new LunchBoxDB(this);
pref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
uid = pref.getString("id", null);
ProductFragment pf = new ProductFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, pf).commit();
sessionManager = new SessionManager(this);
toolbar.setNavigationIcon(R.mipmap.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(this);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment frag = null;
int itemId = item.getItemId();
if (itemId == R.id.nav_home) {
drawerLayout.closeDrawers();
Intent i = new Intent(HomeActivity.this, HomeActivity.class);
startActivity(i);
HomeActivity.this.finish();
} else if (itemId == R.id.nav_profile) {
frag = new AccountFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).addToBackStack("Account").commit();
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_order) {
drawerLayout.closeDrawers();
OrdersFragment of = new OrdersFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, of).addToBackStack("Orders").commit();
} else if (itemId == R.id.nav_store_locator) {
Intent i = new Intent(HomeActivity.this, LocationActivity.class);
startActivity(i);
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_logout) {
drawerLayout.closeDrawers();
sessionManager.logoutUser();
} else if (itemId == R.id.nav_help) {
drawerLayout.closeDrawers();
Intent i = new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:+918460765785"));
startActivity(i);
} else if (itemId == R.id.nav_corpinquiry) {
drawerLayout.closeDrawers();
CorpInquiryFragment crpf = new CorpInquiryFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, crpf).addToBackStack("CorpInquiry").commit();
}
return false;
}
});
}
private void setNavigationDrawer() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.nav_drawer, menu);
final MenuItem alertMenuItem = menu.findItem(R.id.shopping_bag);
FrameLayout rootView = (FrameLayout) alertMenuItem.getActionView();
redCircle = (FrameLayout) rootView.findViewById(R.id.view_alert_red_circle);
countTextView = (TextView) rootView.findViewById(R.id.view_alert_count_textview);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(alertMenuItem);
}
});
badgeupdate();
return super.onCreateOptionsMenu(menu);
}
void badgeupdate() {
SQLiteDatabase db = lunchBoxDB.getReadableDatabase();
String query = "select sum(quantity) from cart where uid = " + uid;
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
totalquantity = c.getInt(0);
}
c.close();
cartcount = totalquantity;
countTextView.setText(String.valueOf(cartcount));
redCircle.setVisibility((cartcount > 0) ? VISIBLE : GONE);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.shopping_bag) {
SharedPreferences pref = this.getSharedPreferences("couponPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("discount", null);
editor.apply();
CartFragment cf = new CartFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, cf, "CartFragment").addToBackStack(null).commit();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}/*else if(i==0){
Toast.makeText(this, "Press back again to exit!", Toast.LENGTH_SHORT).show();
i=1;
}*/ else {
//i=0;
super.onBackPressed();
}
}
#Override
protected void onResume() {
super.onResume();
gps = new GPSTracker(this);
}
#Override
public void onClick(View view) {
setNavigationDrawer();
}
}
Logcat error :
FATAL EXCEPTION: main
Process: com.pisac.foodrestaurant, PID: 29700
java.lang.IllegalStateException: Fragment ProductFragment{13525074} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:800)
at com.pisac.foodrestaurant.ProductFragment.onPageSelected(ProductFragment.java:149)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1967)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:685)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:669)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:622)
at com.pisac.foodrestaurant.ProductFragment$1.run(ProductFragment.java:244)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
You have problem with the line
pd.dismiss();
in onPostExecute of your GetUrlData. Put it inside if (isAdded ()) As per the answer of the question you reffered in your question. Your dialog uses the context of the activity.
EDIT
Add an if block in onPageSelected method that checks if Fragment if attached i.e.
#Override
public void onPageSelected(int position) {
if(!isAdded ())
return;
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
Thanks for helping me.
I got the answer.
I added onStop in the ProductFragment code as below :
#Override
public void onStop() {
viewPager1.setAdapter(null);
super.onStop();
}
and update the onResume :
#Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
if(viewPagerSliderAdapter==null){
new GetUrlData(getActivity()).execute();
}
}
Thanks once again.
I have the following fragment.The problem is that every time I launch this the app crashes with the following exception : attempt to invoke virtual method android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext() on a null object reference. From what I understand getActivity is called correctly, however the FragmentActivityTesting does not return any context, I'm not sure why this is the case:
public class FragmentATesting extends Fragment {
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a,container,false);
}
#Override
public void onActivityCreated(Bundle SavedInstanceState){
super.onActivityCreated(SavedInstanceState);
}
#Override
public void onStart() {
super.onStart();
final SessionManager session = new SessionManager(getActivity().getApplicationContext());
TextView username = (TextView) getView().findViewById(R.id.username_info_txt);
HashMap<String,String> userString = session.getUserDetails();
String usernamee = userString.get("username");
username.setText(usernamee);
vote(usernamee);
}
#Override
public void onResume() {
super.onResume();
final SessionManager session = new SessionManager(getActivity().getApplicationContext());
TextView username = (TextView) getView().findViewById(R.id.username_info_txt);
HashMap<String,String> userString = session.getUserDetails();
String usernamee = userString.get("username");
username.setText(usernamee);
vote(usernamee);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void vote(final String userId) {
class UploadImage extends AsyncTask<String, Void, String> {
RequestHandler rh = new RequestHandler();
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("username",userId);
String result = rh.sendPostRequest(SL_URL2, data);
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSONObject jsonObject = null;
String likess = "";
try {
jsonObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
try {
likess = jsonObject.getString("amount");
} catch (JSONException e) {
e.printStackTrace();
}
TextView amount = (TextView) getView().findViewById(R.id.likes_info_txt);
amount.setText(likess + " Likes");
}}
UploadImage ui = new UploadImage();
ui.execute();
}`
It is inside my ViewPager defined as follows:
public class FragmentActivityTesting extends FragmentActivity {
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_activity_testing);
viewPager = (ViewPager) findViewById(R.id.pic_pager);
setStatusBarColor();
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
viewPager.setCurrentItem(1);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("CLOSE_ALL");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
#TargetApi(21)
public void setStatusBarColor() {
Window window = this.getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Integer.valueOf(android.os.Build.VERSION.SDK) >= 21) {
window.setStatusBarColor(this.getResources().getColor(R.color.green));
}
}}
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position ==0) {
fragment = new FragmentATesting();
}
else if (position == 1) {
fragment = new FragmentBTesting();
}
else if (position == 2) {
fragment = new FragmentCTesting();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
I am using NavigationDrawer and replace fragments like this:
ft.setCustomAnimations(
android.R.anim.slide_in_left, android.R.anim.slide_out_right
);
ft.replace(container, fragment);
// Start the animated transition.
ft.commit();
When Application start and First fragment is loaded, allocation heap is ~15 MB.
After I replace first fragment with second and doing some work, allocation heap ~40MB.
Then I replace second fragment with third, allocation heap maintains at ~40MB ( if force garbage collection) allocation heap decreases by ~7 mb.
If, I will not load second fragment and will go to third from first, allocation heap will maintain at ~17 MB.
Is second fragment destroyed at all, and if it is destroyed, why memmory is not freed?
As I understand without addToBackStack() fragments are not added to back stack and should be destroyed after removing ( as replace call remove and add)
Second fragment is basicly a listview
public class ArtistListFragment extends Fragment {
private FragmentArtistAdapter adapter;
private static final List<ArtistsEntity> articles = new ArrayList<>();
private GetAdds feed = new GetAdds();
private GridView list;
private String request = "new";
private ToggleButton tbLeft;
private ToggleButton tbRight;
private ToggleButton tbAbc;
public ArtistListFragment() {
// Required empty public constructor
}
private Tracker t;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
t = ((UILApplication) getActivity().getApplication()).getTracker();
t.setScreenName("Artist List Screen");
t.send(new HitBuilders.EventBuilder()
.setCategory("Open Screen")
.build());
t.send(new HitBuilders.EventBuilder()
.setCategory("view")
.setAction("choose")
.setLabel("new")
.build());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_artist_list, container, false);
setSwipeLayout(view);
eVideoScroll.resetState();
adapter = new FragmentArtistAdapter(getActivity(), articles);
list = (GridView) view.findViewById(R.id.gridview);
tbLeft = (ToggleButton) view.findViewById(R.id.tb_left);
tbRight = (ToggleButton) view.findViewById(R.id.tb_right);
tbAbc = (ToggleButton) view.findViewById(R.id.tb_abc);
tbLeft.setOnCheckedChangeListener(leftListener);
tbRight.setOnCheckedChangeListener(rightListener);
tbAbc.setOnCheckedChangeListener(abcListener);
tbLeft.setClickable(false);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
BusProvider.getInstance().post(new OpenArtistInfo(
articles.get(position)
.getSlug()));
}
});
feed = new GetAdds();
feed.execute();
list.setOnScrollListener(eVideoScroll);
return view;
}
private SwipeRefreshLayout swipeLayout;
private void setSwipeLayout(View view) {
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(refreshPage);
swipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
private final SwipeRefreshLayout.OnRefreshListener refreshPage = new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new ResetVideoSelection().execute();
}
};
boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle(getString(R.string.no_internet_conection));
alertDialog
.setMessage(getString(R.string.open_network_settings));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes_response),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no_response),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
return false;
}
}
void emptyResultDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(ErrorMessage.INSTANCE.getErrorMessage())
.setCancelable(false)
.setPositiveButton(R.string.close_response,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
Dialog dialog = builder.create();
dialog.show();
}
private class GetAdds extends AsyncTask<Void, Void, List<ArtistsEntity>> {
#Override
protected void onPreExecute() {
if (!checkInternetConnection()) {
swipeLayout.setRefreshing(true);
cancel(true);
eVideoScroll.loading = false;
} else {
if (!swipeLayout.isRefreshing())
swipeLayout.setRefreshing(true);
}
}
#Override
protected List<ArtistsEntity> doInBackground(Void... params) {
int trial = 0;
MaterialRequest jParse = new MaterialRequest();
List<ArtistsEntity> result = null;
int page = PaggingData.INSTANCE.artistListCurrentPage + 1;
while (result == null && trial < 5 && !isCancelled()) {
trial++;
result = jParse.getArtists(request, page);
}
return result;
}
#Override
protected void onPostExecute(List<ArtistsEntity> result) {
super.onPostExecute(result);
if (result != null && result.size() > 0) {
if (PaggingData.INSTANCE.artistListCurrentPage <= 1)
articles.clear();
articles.addAll(result);
adapter.notifyDataSetChanged();
} else
emptyResultDialog();
eVideoScroll.loading = false;
swipeLayout.setRefreshing(false);
}
}
private final CompoundButton.OnCheckedChangeListener leftListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
request = "new";
new ResetVideoSelection().execute();
tbRight.setChecked(false);
tbAbc.setChecked(false);
tbLeft.setClickable(false);
t.send(new HitBuilders.EventBuilder()
.setCategory("view")
.setAction("choose")
.setLabel("new")
.build());
} else {
tbLeft.setClickable(true);
}
}
};
private final CompoundButton.OnCheckedChangeListener rightListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
request = "popular";
new ResetVideoSelection().execute();
tbLeft.setChecked(false);
tbAbc.setChecked(false);
tbRight.setClickable(false);
t.send(new HitBuilders.EventBuilder()
.setCategory("view")
.setAction("choose")
.setLabel("popular")
.build());
} else {
tbRight.setClickable(true);
}
}
};
private final CompoundButton.OnCheckedChangeListener abcListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
request = "abc";
new ResetVideoSelection().execute();
tbRight.setChecked(false);
tbLeft.setChecked(false);
tbAbc.setClickable(false);
t.send(new HitBuilders.EventBuilder()
.setCategory("view")
.setAction("choose")
.setLabel("abc")
.build());
} else {
tbAbc.setClickable(true);
}
}
};
private class ResetVideoSelection extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
eVideoScroll.resetState();
list.setSelection(0);
}
#Override
protected Void doInBackground(Void... params) {
// if (videoArticles.size() > 0)
// while (listVideo.getSelectedItemPosition() != 0) {
//
// }
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
feed = new GetAdds();
feed.execute();
}
}
private final EndlessVideoScrollListener eVideoScroll = new EndlessVideoScrollListener();
private class EndlessVideoScrollListener implements AbsListView.OnScrollListener {
private int visibleThreshold = 5;
private int previousTotal = 0;
private boolean loading = true;
public void resetState() {
visibleThreshold = 5;
previousTotal = 0;
loading = true;
PaggingData.INSTANCE.artistListPages = 0;
PaggingData.INSTANCE.artistListCurrentPage = 0;
}
public EndlessVideoScrollListener() {
}
public EndlessVideoScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
// loading = false;
previousTotal = totalItemCount;
}
}
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
if (PaggingData.INSTANCE.artistListCurrentPage + 1 <= PaggingData.INSTANCE.artistListPages) {
feed = new GetAdds();
feed.execute();
loading = true;
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
#Override
public void onPause() {
super.onPause();
feed.cancel(true);
swipeLayout.setRefreshing(false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((NavigationDrawerActivity) activity).onSectionAttached(getArguments().getString("title"));
}
}
Indeed, Fragments are destroyed and created anew as they shift in and out of view (unlike Activitys), provided addToBackStack() is not used.
I suspect that
1. You have set android:largeHeap = true in your app manifest.
2. Your Fragments are possibly making use of heavy ImageViews / VideoViews or cached Bitmaps with static references, which can also be a cause of unrestricted heap growth.
These are some reasons off the top of my head that I can think of in a situation like this.