Flipping game logic help required - java

i am working on a small game and i have written logic already, game shows 4 rows and 3 columns means total 12 cells or buttons.
they appear 2 seconds and i show all the icons on it and after that i disappear them, then user has to match the icons to complete the game.
I am using gridview for this purpose and code is given below of my entire game logic, but clicking on the button is very slow any one guide me why my game is slow onclicking the cell and how can i improve it?
public class GameScreenFragment extends Fragment implements AdapterView.OnItemClickListener {
int i = 0;
private GridView gridView;
private TextView textViewShowTime;
public int[] tapherePictureArray = {R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here, R.drawable.tap_here};
public int[] objectPictureArray = {R.drawable.bettry, R.drawable.htc_logo, R.drawable.uber, R.drawable.uber, R.drawable.htc_name, R.drawable.qualocommi, R.drawable.hi_res_audio, R.drawable.qualocommi, R.drawable.bettry, R.drawable.htc_name, R.drawable.htc_logo, R.drawable.hi_res_audio};
public int[] intervalObjectArray = {R.drawable.bettry, R.drawable.htc_logo, R.drawable.uber, R.drawable.uber, R.drawable.htc_name, R.drawable.qualocommi, R.drawable.hi_res_audio, R.drawable.qualocommi, R.drawable.bettry, R.drawable.htc_name, R.drawable.htc_logo, R.drawable.hi_res_audio};
public ArrayList<Integer> listRandomObjectPicture;
public ArrayList<Integer> listRandomIntervalObjectPicture;
MainActivity context;
ImageAdapter imageAdapter;
int isttId, secondId;
int oddpos, evenpos;
Chronometer stopWatch;
long startTime;
public ArrayList<Integer> disableposition;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_game_screen, null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gridView = (GridView) view.findViewById(R.id.grid_view);
textViewShowTime = (TextView) view.findViewById(R.id.textView_show_time);
stopWatch = (Chronometer) view.findViewById(R.id.chrono);
gridView.setOnItemClickListener(this);
}
CountDownTimer countDownTimer;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
disableposition = new ArrayList<>();
context = (MainActivity) getActivity();
imageAdapter = new ImageAdapter(context, intervalObjectArray, disableposition);
gridView.setAdapter(imageAdapter);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageAdapter = new ImageAdapter(context, tapherePictureArray, disableposition);
gridView.setAdapter(imageAdapter);
startTime = SystemClock.elapsedRealtime();
countDownTimer = new CountDownTimer(45000, 1000) {
public void onTick(long millisUntilFinished) {
textViewShowTime.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
countDownTimer.cancel();
textViewShowTime.setText("00");
new AlertDialog.Builder(context)
.setTitle("Time Up")
.setCancelable(false)
.setMessage("Oops! Looks like you ran out of time. try it again")
.setPositiveButton("try again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
countDownTimer.cancel();
context.replaceFragmentWithoutBackstack(new GameScreenFragment());
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
};
countDownTimer.start();
}
}, 2000);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
i++;
Log.e("counter", i + "");
if ((i % 2) == 0) {
secondId = objectPictureArray[position];
evenpos = position;
tapherePictureArray[position] = objectPictureArray[position];
imageAdapter.notifyDataSetChanged();
gridView.invalidateViews();
if (isttId == secondId && evenpos != oddpos) {
tapherePictureArray[oddpos] = objectPictureArray[oddpos];
tapherePictureArray[evenpos] = objectPictureArray[evenpos];
disableposition.add(oddpos);
disableposition.add(evenpos);
Log.e("Size", disableposition.size() + "");
imageAdapter.notifyDataSetChanged();
gridView.invalidateViews();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (disableposition.size() == 12) {
countDownTimer.cancel();
context.winTime = textViewShowTime.getText().toString();
int temptime = Integer.parseInt(context.winTime);
int actualTime = 45 - temptime;
context.winTime = String.valueOf(actualTime);
context.fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
context.replaceFragment(new TimerShowFragment());
}
}
}, 500);
} else {
i = 0;
tapherePictureArray[position] = objectPictureArray[position];
imageAdapter.notifyDataSetChanged();
gridView.invalidateViews();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
tapherePictureArray[evenpos] = R.drawable.tap_here;
tapherePictureArray[oddpos] = R.drawable.tap_here;
imageAdapter.notifyDataSetChanged();
gridView.invalidateViews();
}
}, 300);
}
} else {
oddpos = position;
isttId = objectPictureArray[position];
tapherePictureArray[position] = objectPictureArray[position];
imageAdapter.notifyDataSetChanged();
gridView.invalidateViews();
}
}
#Override
public void onResume() {
super.onResume();
if (countDownTimer != null) {
countDownTimer.cancel();
}
}
#Override
public void onPause() {
super.onPause();
if (countDownTimer != null) {
countDownTimer.cancel();
}
}
}

Related

Is it possible to set ViewPager inside a fragment class?

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().

After clicking on song from the listview,new activity is opening but song is not playing

I am creating a musicplayer app.for that iam getting list of song from device but when iam clicking on song new activity is opening but song is not playing its just opening the activity thats it
I check checked code many times but didnt find any solution
if i use different method for getting device songs then its working but that method not finding all songs but only few songs.
playlist activity
public class PlayListActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_READ = 7;
private static final int REQUEST_PERMISSION = 5;
private static final int MY_PERMISSIONS_REQUEST_READ_MEDIA = 99;
public static ArrayList<TrackObjects> songsList;
private ListView songView;
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
songView = (ListView) findViewById(R.id.songlist);
songsList = new ArrayList<TrackObjects>();
songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long l) {
Intent i1 = new Intent(PlayListActivity.this, MainActivity.class);
i1.putExtra("pos", position);
i1.putExtra("songs", songsList);
startActivity(i1);
}
});
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
Collections.sort(songsList, new Comparator<TrackObjects>() {
public int compare(TrackObjects a, TrackObjects b) {
return a.getTitle().compareTo(b.getTitle());
}
});
TracksAdapter songAdt = new TracksAdapter(PlayListActivity.this, songsList);
songView.setAdapter(songAdt);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
} else {
getSongList();
}
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst()) {
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songsList.add(new TrackObjects(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_MEDIA:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
getSongList();
}
break;
default:
break;
}
}
}
MainActivity(Songs Playing activity) :
public class MainActivity extends AppCompatActivity {
static MediaPlayer mp;
int position;
SeekBar sb;
ArrayList mySongs;
Thread updateSeekBar;
ImageButton pause, forward, reverse, next, previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pause = (ImageButton) findViewById(R.id.pause);
forward = (ImageButton) findViewById(R.id.forward);
previous = (ImageButton) findViewById(R.id.previous);
next = (ImageButton) findViewById(R.id.next);
reverse = (ImageButton) findViewById(R.id.reverse);
sb = (SeekBar) findViewById(R.id.seekBar);
updateSeekBar = new Thread() {
#Override
public void run() {
int totalDuration = mp.getDuration();
int currentPosition = 0;
while (currentPosition < totalDuration) {
try {
sleep(500);
currentPosition = mp.getCurrentPosition();
sb.setProgress(currentPosition);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
if (mp != null) {
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
assert b != null;
mySongs = (ArrayList) b.getParcelableArrayList("songs");
position = b.getInt("pos",0);
Uri u = Uri.parse(mySongs.get(position).toString());
if (mp!=null) {
mp= (MediaPlayer) MediaPlayer.create(MainActivity.this, u);
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i,
boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
if (mp.isPlaying()) {
pause.setBackgroundResource(R.mipmap.play_button);
mp.pause();
} else {
pause.setBackgroundResource(R.mipmap.pause);
mp.start();
}
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
mp.seekTo(mp.getCurrentPosition() + 5000);
}
});
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
mp.seekTo(mp.getCurrentPosition() - 5000);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.release();
position = ((position + 1) % mySongs.size());
Uri u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.release();
position = ((position - 1) < 0) ? (mySongs.size() - 1) : (position - 1);
Uri u = Uri.parse(mySongs.get(
position).toString());//%mysongs so that it do not go to invalid position
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
}
});
}
}
}
TracksAdapter(Songslist adapter) :
public class TracksAdapter extends BaseAdapter {
private ArrayList<TrackObjects> tracks;
private LayoutInflater trackInf;
public TracksAdapter(Context c, ArrayList<TrackObjects> theTracks) {
tracks = theTracks;
trackInf = LayoutInflater.from(c);
}
#Override
public int getCount() {
return tracks.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//map to song layout
#SuppressLint("ViewHolder") LinearLayout songLay = (LinearLayout) trackInf.inflate
(R.layout.songtracks, parent, false);
//get title and artist views
TextView trackView = (TextView) songLay.findViewById(R.id.track_title);
TextView artistView = (TextView) songLay.findViewById(R.id.track_artist);
//get song using position
TrackObjects currSong = tracks.get(position);
//get title and artist strings
trackView.setText(currSong.getTitle());
artistView.setText(currSong.getArtist());
//set position as tag
songLay.setTag(position);
return songLay;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
TrackObjects(Objects class) :
public class TrackObjects implements Serializable {
private long id;
private String title;
private String artist;
public TrackObjects(long id, String title, String artist) {
this.id = id;
this.title = title;
this.artist = artist;
}
protected TrackObjects(Parcel in) {
id = in.readLong();
title = in.readString();
artist = in.readString();
}
public long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
{
}}
The problem is that you are not passing url to the media player in your MainActivity. Your code is something like:
mySongs = (ArrayList) b.getParcelableArrayList("songs");
position = b.getInt("pos",0);
Uri u = Uri.parse(mySongs.get(position).toString());
Here,
mySongs.get(position).toString();
It will return TrackObjects from list and using toString() will return object reference data. So ultimately you are not passing any url to the media player.
Solution:
Add a new string variable in TrackObjects class such as private String songUrl; and to get this use following line instead of above line
Uri u = Uri.parse(mySongs.get(position).getSongUrl());
Hope it will solve your issue.

Basic music player - next and previous button

this is my last post about any kind of music player ever but I really need help. Im working on basic android music player application and Im having trouble to create NEXt and PREVIOUS buttons. So i pretty pretty please if anyone can get me out of that.I have tried something more about that downhere THANK YOU. I have created this yet:
Main Application Java file
public class MainActivity extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile= null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton previousButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingseekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
selectedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
previousButton = (ImageButton) findViewById(R.id.previous);
nextButton = (ImageButton) findViewById(R.id.next);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
previousButton.setOnClickListener(onButtonClick);
}
}
#Override
protected void onListItemClick(ListView list, View view, int position,long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
#Override
protected void onDestroy(){
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
selectedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e){
e.printStackTrace();
} catch (IllegalStateException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
// seekbar.setSecondaryProgressTintMode(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter{
MediaCursorAdapter(Context context, int layout, Cursor c){
super(context, layout,c,
new String[] {MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[] {R.id.displayname, R.id.title,R.id.duration});
}
#Override
public void bindView(View view,Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto < player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.previous: {
int seekto = player.getCurrentPosition() - STEP_VALUE;
if (seekto < player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingseekBar = false;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fomUser) {
if (isMovingseekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChange");
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingseekBar = true;
}
};
}
I have already did switch with NEXT and PREVIOUS buttons and I have tried to make them work BUT I ended up with getting at the and or beggining of the song not the NEXT or PREVIOUS.

Slide Show using ViewPager and Timer in Android

I have created a very simple slide show using viewpager. To auto slide I have used a timer for every 5 seconds. I have a X button to close the slide show in the middle of the slide. When I press the X the app closes the slideshow goes to MainActivity. All this is working fine but when I open the slideshow activity
again from MainActivity the first image comes up properly but then the next one jumps to last image from the array, doesn't show other images. Could be timer issue or something else. I am purging and cancelling the timer
Please check my code below:
I have set the images in Array and adding them to arrayList.
private static final Integer[] LANDSCAPEIMAGES = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5,
R.drawable.image6, R.drawable.image7, R.drawable.image8, R.drawable.image9, R.drawable.image10,
R.drawable.image11};
private ArrayList<Integer> imagesArray = new ArrayList<Integer>();
private Timer swipeTimer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.slideshow);
swipeTimer = new Timer();
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//init();
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//init();
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
initLand();
}
mPager.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
}
private void initLand()
{
for (int i = 0; i < LANDSCAPEIMAGES.length; i++)
imagesArray.add(LANDSCAPEIMAGES[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new SlidingImage_Adapter(StartSlideShow.this, imagesArray, this));
NUM_PAGES = LANDSCAPEIMAGES.length;
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable()
{
public void run()
{
//Comment for no loop.
/*if (currentPage == NUM_PAGES) {
currentPage = 0;
}*/
mPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer.schedule(new TimerTask() {
#Override
public void run()
{
handler.post(Update);
}
}, 5000, 5000);
}
//TO FINISH THE ACTIVITY AND STOP TIMER()
#Override
public void pagerItemSelected()
{
Log.e("Value", "=It is coming here");
finish();
onBackPressed();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Log.e("Value", "=onBackPressed");
swipeTimer.purge();
swipeTimer.cancel();
}
My PagerAdapter:
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
OnPagerItemSelected mListener;
public SlidingImage_Adapter(Context context,ArrayList<Integer> IMAGES, OnPagerItemSelected listener) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
mListener = listener;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position)
{
View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false);
ImageView quit = (ImageView) imageLayout.findViewById(R.id.closeimage);
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent readMore = new Intent(v.getContext(), MainActivity.class);
v.getContext().startActivity(readMore);
// ((Activity) context).finish();
mListener.pagerItemSelected();
}
});
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
Log.e("Value"," - " + position);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
public interface OnPagerItemSelected {
void pagerItemSelected();
}
}

Android - Why RAM usage continues to increase after fragment replace?

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.

Categories

Resources