on back pressed I want to go previous activity from adapter - java

I have an activity which is connected with an adapter. In the activity, I include adapter layout. when I click on the button than adapter layout open but when I press back button in adapter layout than automatically reached main activity. I want that when I press back button in adapter than go to previous activity.
activity code is below
public class TestFragment extends Fragment {
private Button btnA,
btnB,
btnC,
btnD,
btnSubmit,
btnNext,
btnPrev,
btnFlag;
private TextView tvQuestion,
tvLayout;
private int totalItem;
private int listItem = 0;
private ArrayList < mcqQuestion > quesList = new ArrayList < >();
private int score = 0;
private boolean isLoading = true;
private RelativeLayout rlMcqProgress;
private FirebaseAuth mAuth;
private boolean allAnswered = false;
private RecyclerView rvQuesLayout;
private RecyclerView.LayoutManager layoutManager;
private QuestionLayoutRecyclerAdapter adapter;
private LinearLayout llQuestionAll;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference("tax").child("Questions");
public TestFragment() {
// Required empty public constructor
}#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_test, container, false);
btnA = view.findViewById(R.id.btn_mcq_A);
btnB = view.findViewById(R.id.btn_mcq_B);
btnC = view.findViewById(R.id.btn_mcq_C);
btnD = view.findViewById(R.id.btn_mcq_D);
btnSubmit = view.findViewById(R.id.btn_mcq_submit);
btnNext = view.findViewById(R.id.btn_mcq_next);
btnPrev = view.findViewById(R.id.btn_mcq_prev);
btnFlag = view.findViewById(R.id.btn_mcq_flag);
tvQuestion = view.findViewById(R.id.tv_mcq_question);
tvLayout = view.findViewById(R.id.tv_mcq_question_layout);
rvQuesLayout = view.findViewById(R.id.rv_layout_question_test);
rlMcqProgress = view.findViewById(R.id.rl_mcq_progress);
rlMcqProgress.setVisibility(View.VISIBLE);
llQuestionAll = view.findViewById(R.id.ll_test_all);
mAuth = FirebaseAuth.getInstance();
getFData();
btnA.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optA");
setButtonColor();
btnA.setBackgroundResource(R.color.sky_blue);
}
});
btnB.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optB");
setButtonColor();
btnB.setBackgroundResource(R.color.sky_blue);
}
});
btnC.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optC");
setButtonColor();
btnC.setBackgroundResource(R.color.sky_blue);
}
});
btnD.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optD");
setButtonColor();
btnD.setBackgroundResource(R.color.sky_blue);
}
});
btnFlag.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
setFlagValue();
setFlagColor();
}
});
tvLayout.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
adapter.notifyDataSetChanged();
if (rvQuesLayout.getVisibility() == View.GONE || rvQuesLayout.getVisibility() == View.INVISIBLE) {
rvQuesLayout.setVisibility(View.VISIBLE);
llQuestionAll.setVisibility(View.GONE);
} else {
rvQuesLayout.setVisibility(View.GONE);
llQuestionAll.setVisibility(View.VISIBLE);
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
displayNextQues();
}
});
btnPrev.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
displayPrevQues();
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {#SuppressLint("SetTextI18n")#Override
public void onClick(View v) {
for (int i = 0; i < totalItem; i++) {
if (quesList.get(i).getSelAnswer().equals("none")) {
allAnswered = false;
score++;
break;
} else {
if (quesList.get(i).getSelAnswer().equals(quesList.get(i).getAnswer())) {
score++;
}
allAnswered = true;
}
}
if (allAnswered) {
Intent intent = new Intent(this, finalresult.class);
intent.putExtra("score", score);
intent.putExtra("questions", totalItem);
startActivity(intent);
} else {
Toast.makeText(this, "Answer all the questions", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void makeRecyclerView() {
layoutManager = new LinearLayoutManager(this);
//rvQuesLayout.setHasFixedSize(true);
rvQuesLayout.setLayoutManager(layoutManager);
adapter = new QuestionLayoutRecyclerAdapter(quesList);
rvQuesLayout.setAdapter(adapter);
adapter.setOnItemClickListner(new QuestionLayoutRecyclerAdapter.onItemClickListner() {#Override
public void onClick(int pos) {
listItem = pos;
if (listItem >= 0 && listItem < totalItem) {
makeAllDisplay();
rvQuesLayout.setVisibility(View.GONE);
llQuestionAll.setVisibility(View.VISIBLE);
}
}
});
}
private void setDisplay(int item) {
btnA.setText(quesList.get(item).getOptA());
btnB.setText(quesList.get(item).getOptB());
btnC.setText(quesList.get(item).getOptC());
btnD.setText(quesList.get(item).getOptD());
tvQuestion.setText(quesList.get(item).getQuestion());
}
private void getFData() {
myRef.addValueEventListener(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
String qtext = (String) messageSnapshot.child("qText").getValue();
String optA = (String) messageSnapshot.child("optA").getValue();
String optB = (String) messageSnapshot.child("optB").getValue();
String optC = (String) messageSnapshot.child("optC").getValue();
String optD = (String) messageSnapshot.child("optD").getValue();
String answer = (String) messageSnapshot.child("answer").getValue();
quesList.add(new mcqQuestion(qtext, optA, optB, optC, optD, answer, "none", false));
Log.d("TOTAL ITEM", String.valueOf(quesList.size()));
}
totalItem = quesList.size();
isLoading = false;
if (!isLoading) {
setDisplay(listItem);
rlMcqProgress.setVisibility(View.GONE);
tvLayout.setVisibility(View.VISIBLE);
}
makeRecyclerView();
}#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void setFlagValue() {
if (quesList.get(listItem).isFlag()) {
quesList.get(listItem).setFlag(false);
} else {
quesList.get(listItem).setFlag(true);
}
}
private void setFlagColor() {
if (quesList.get(listItem).isFlag()) {
btnFlag.setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.black));
btnFlag.setTextColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey));
} else {
btnFlag.setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey_light));
btnFlag.setTextColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey));
}
}
private void setButtonColor() {
btnA.setBackgroundResource(R.color.grey_light);
btnB.setBackgroundResource(R.color.grey_light);
btnC.setBackgroundResource(R.color.grey_light);
btnD.setBackgroundResource(R.color.grey_light);
}
private void displayNextQues() {
if (listItem < totalItem - 1) {
listItem++;
makeAllDisplay();
} else {
btnNext.setVisibility(View.GONE);
btnSubmit.setVisibility(View.VISIBLE);
}
}
private void makeAllDisplay() {
setDisplay(listItem);
setButtonColor();
setFlagColor();
switch (quesList.get(listItem).getSelAnswer()) {
case "optA":
btnA.setBackgroundResource(R.color.sky_blue);
break;
case "optB":
btnB.setBackgroundResource(R.color.sky_blue);
break;
case "optC":
btnC.setBackgroundResource(R.color.sky_blue);
break;
case "optD":
btnD.setBackgroundResource(R.color.sky_blue);
break;
default:
setButtonColor();
break;
}
}
private void displayPrevQues() {
btnNext.setVisibility(View.VISIBLE);
if (listItem > 0 && listItem < totalItem) {
listItem--;
makeAllDisplay();
} else {
Toast.makeText(this, "Cannot GO back!!", Toast.LENGTH_SHORT).show();
}
}
}
and the adapter code is below
public class QuestionLayoutRecyclerAdapter extends RecyclerView.Adapter < QuestionLayoutRecyclerAdapter.FlagViewHolder > {
private ArrayList < mcqQuestion > quesList;
private onItemClickListner onItemClickListner;
public void setOnItemClickListner(QuestionLayoutRecyclerAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(int pos); //pass your object types.
}
public QuestionLayoutRecyclerAdapter(ArrayList < mcqQuestion > quesList) {
this.quesList = quesList;
}
#NonNull#Override
public FlagViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(layout.question_layout, parent, false);
FlagViewHolder flagViewHolder = new FlagViewHolder(view, quesList);
return flagViewHolder;
}
#SuppressLint("ResourceAsColor")#Override
public void onBindViewHolder(#NonNull final FlagViewHolder holder, int position) {
mcqQuestion question_id = quesList.get(position);
holder.tvQuestionNumber.setText("Question " + (position + 1));
if (question_id.isFlag()) {
holder.ivFlag.setImageResource(drawable.right2);
} else {
holder.ivFlag.setImageResource(drawable.white2);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
onItemClickListner.onClick(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return quesList.size();
}
public static class FlagViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView ivFlag;
TextView tvQuestionNumber;
ArrayList < mcqQuestion > quesList;
public FlagViewHolder(#NonNull View itemView, ArrayList < mcqQuestion > quesList) {
super(itemView);
ivFlag = itemView.findViewById(id.iv_layout_flag);
tvQuestionNumber = itemView.findViewById(id.tv_layout_question_number);
itemView.setOnClickListener(this);
this.quesList = quesList;
}
#Override
public void onClick(View v) {
int quesClick = getAdapterPosition();
}
}
}

Try this
#Override
public void onBackPressed()
{
Intent intent = new Intent(this, ActivityWhereYouWantToGo.class);
startActivity(intent);
}

As per you code, you are not navigation to another screen you are only changing the Visibility. On back press, you can check which view is currently displaying and handle accordingly.
#Override
public void onBackPressed() {
if (findViewById(R.id.your_view).visibility == View.Visible) {
//change your visibility
rvQuesLayout.setVisibility(View.VISIBLE);
llQuestionAll.setVisibility(View.GONE);
//reverse the things you did in makeAllDisplay() method
} else {
super.onBackPressed();
}
}

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

How can I pause exoplayer when i swipe ViewPager2?

I am using viewpager2 with exoplayer, videos (from firebase). When i am swiping through videos, the videos keep playing, i have to stop it myself by swiping again to the playing video and clicking on exoplayer pause button. I want the videos to stop automatically when i swipe viewpager2.
How can i stop the video onswipe? by the way, i am very new to coding in general and even on this website, so i wish to get help and not to bother anyone.
This is the class i am implementing viewpager2:
public class Dashboard extends AppCompatActivity {
private static final String TAG = "Dashboard";
private static final int ACTIVITY_NUM = 0;
private static final int CAMERA_PERMISSION_REQUEST_CODE = 88888;
private Context xContext = Dashboard.this;
int likescount;
DatabaseReference likesref;
//uis
ViewPager2 viewPager2;
FirebaseUser firebaseUser;
boolean flag = false;
DatabaseReference likesrefernce = FirebaseDatabase.getInstance().getReference("likes");
Boolean likechecker = false;
String profileid;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
Log.d(TAG, "onCreate: started.");
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (firebaseUser != null) {
firebaseUser.getUid();
}
setupBottomNavigationView();
// getSupportActionBar().setTitle("Videos");
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
viewPager2 = (ViewPager2) findViewById(R.id.vpager);
}
FirebaseRecyclerOptions<video> options =
new FirebaseRecyclerOptions.Builder<video>()
.setQuery(FirebaseDatabase.getInstance().getReference("video"), video.class)
.build();
FirebaseRecyclerAdapter<video, ViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<video, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull video member) {
SharedPreferences prefs = xContext.getSharedPreferences("PREFS", MODE_PRIVATE);
profileid = prefs.getString("profileid", "none");
holder.setExoplayer(getApplication(), member.getName(), member.getVideourl());
FirebaseUser user1 = FirebaseAuth.getInstance().getCurrentUser();
assert user1 != null;
String currentUserId = user1.getUid();
String userId = user1.getUid();
final String i = getRef(position).getKey();
final String publisher = getRef(position).getKey();
DatabaseReference reference3 = FirebaseDatabase.getInstance().getReference("Users").child(member.getPublisher());
reference3.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (getApplicationContext() == null) {
return;
}
User user3 = dataSnapshot.getValue(User.class);
Glide.with(getApplicationContext()).load(user3 != null ? user3.getImageurl() : null).into(holder.image_profile);
holder.username.setText(user3 != null ? user3.getUsername() : null);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
likesref = FirebaseDatabase.getInstance().getReference("likes");
String likes = "likes";
likesref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(i).hasChild(userId)) {
likescount = (int) dataSnapshot.child(i).getChildrenCount();
holder.lovers.setImageResource(R.drawable.ic_love2);
holder.lovers_text.setText(Integer.toString(likescount));
} else {
likescount = (int) dataSnapshot.child(i).getChildrenCount();
holder.lovers.setImageResource(R.drawable.ic_love);
holder.lovers_text.setText(Integer.toString(likescount));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.lovers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
likechecker = true;
likesrefernce.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (likechecker.equals(true)) {
if (dataSnapshot.child(i).hasChild(currentUserId)) {
likesrefernce.child(i).child(currentUserId).removeValue();
likechecker = false;
} else {
likesrefernce.child(i).child(currentUserId).setValue(true);
likechecker = false;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
holder.comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(xContext, CommentsVideos.class);
intent.putExtra("i", i);
xContext.startActivity(intent);
}
});
holder.comments_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(xContext, CommentsVideos.class);
intent.putExtra("i", i);
xContext.startActivity(intent);
}
});
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = xContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", member.getPublisher());
editor.apply();
Intent intent = new Intent(xContext, Profile.class);
xContext.startActivity(intent);
}
});
holder.Notification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Dashboard.this, Notifications.class);
startActivity(intent);
}
});
holder.btFullScreen.setOnClickListener(new View.OnClickListener() {
#SuppressLint("UseCompatLoadingForDrawables")
#Override
public void onClick(View view) {
//check condition
if (flag) {
//when flag is true
//set enter full screen image
//set portrait orientation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavViewBar);
bottomNavigationView.setVisibility(View.GONE);
flag = false;
} else {
//when flag is false, set exit full screen image
holder.btFullScreen.setImageDrawable(getResources().getDrawable(R.drawable.ic_cross));
//set landscape orientation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavViewBar);
bottomNavigationView.setVisibility(View.GONE);
//set flag value is true
flag = true;
}
}
});
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.syco, parent, false);
return new ViewHolder(view);
}
};
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
viewPager2.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStop() {
super.onStop();
firebaseRecyclerAdapter.stopListening();
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView () {
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationView);
BottomNavigationViewHelper.enableNavigation(xContext, bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
#Override
protected void onResume () {
super.onResume();
checkPermission();
}
// initializeplayer();
private void checkPermission () {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
// request camera permission if it has not been grunted.
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult ( int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults){
switch (requestCode) {
case CAMERA_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Dashboard.this, "permission has been grunted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Dashboard.this, "[WARN] permission is not grunted.", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
This is viewholder:
public class ViewHolder extends RecyclerView.ViewHolder {
private final Context context = null;
SimpleExoPlayer exoPlayer;
//Initialize variable
PlayerView playerView;
ProgressBar progressBar;
//uis
ImageView comments, lovers, btFullScreen;
private SimpleExoPlayer player;
TextView lovers_text;
TextView comments_text;
TextView username1;
TextView rTitleTv2, Notification, Challenges, username;
CircleImageView image_profile;
private User user2 = new User();
Boolean finished;
DatabaseReference reference1;
int likescount;
int commentscount;
DatabaseReference likesref, postref;
private ViewPager2 ViewPager2;
private OnScrollListener OnScrollListener;
MediaSource renderers;
FirebaseUser firebaseUser;
private Comment comment = new Comment();
private video video = new video();
public ViewHolder(#NonNull View itemView) {
super(itemView);
//uis
image_profile = itemView.findViewById(R.id.image_profile);
username = itemView.findViewById(R.id.username);
comments = itemView.findViewById(R.id.comments);
comments_text = itemView.findViewById(R.id.comments_text);
rTitleTv2 = itemView.findViewById(R.id.rTitleTv2);
Notification = itemView.findViewById(R.id.Notification);
Challenges = itemView.findViewById(R.id.Challenges);
btFullScreen = itemView.findViewById(R.id.bt_fullscreen);
lovers = itemView.findViewById(R.id.lovers);
lovers_text = itemView.findViewById(R.id.lovers_text);
}
public void setExoplayer(Application application, String name, String Videourl){
TextView textView = itemView.findViewById(R.id.rTitleTv2);
playerView = itemView.findViewById(R.id.player_view);
progressBar = itemView.findViewById(R.id.progressBar);
ImageView exo_pause = itemView.findViewById(R.id.exo_pause);
ImageView exo_play = itemView.findViewById(R.id.exo_play);
textView.setText(name);
try {
//Initialize load control
LoadControl loadControl = new DefaultLoadControl();
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter.Builder(application).build();
TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
exoPlayer = (SimpleExoPlayer) ExoPlayerFactory.newSimpleInstance(application);
Uri video = Uri.parse(Videourl);
DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("video");
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource(video,dataSourceFactory,extractorsFactory,null,null);
playerView.setPlayer(exoPlayer);
//keep screen on
playerView.setKeepScreenOn(true);
exoPlayer.prepare(mediaSource);
exoPlayer.setPlayWhenReady(true);
// ...enable autoplay...
}catch (Exception e){
Log.e("ViewHolder","exoplayer error"+e.toString());
}
if (exoPlayer == null){
exo_pause.setImageDrawable(application.getResources().getDrawable(R.drawable.ic_play));
}
exoPlayer.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason){
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == STATE_BUFFERING){
//when buffering show progress bar
progressBar.setVisibility(View.VISIBLE);
} else if (playbackState == STATE_READY){
//when ready hide
progressBar.setVisibility(View.GONE);
exoPlayer.isPlaying();
}
if (playbackState == STATE_ENDED){
//when ready hide
exoPlayer.isPlaying();
exoPlayer.getRepeatMode();
}
}
#Override
public void onRepeatModeChanged(int repeatMode ) {
exo_play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (exoPlayer != null){
exoPlayer.getRepeatMode();
}
}
});
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed(){
}
});
}
}
#Override
public void onViewAttachedToWindow(#NonNull FootballViewHolder holder) {
super.onViewAttachedToWindow(holder);
if(holder.playerView.getPlayer() != null) {
holder.playerView.getPlayer().play();
}
}`
#Override
public void onViewDetachedFromWindow(#NonNull FootballViewHolder holder{
super.onViewDetachedFromWindow(holder);
if(holder.playerView.getPlayer() != null) {
holder.playerView.getPlayer().pause();
}
}
You need to use this inside the adapter class.

Load next item of reyclerview when user clicks on next button, having error in this

I am making an android app in which i have reyclerview whenever user clicks on recyclerview items then he is navigating to next activity and in next activity data will be shown. It is working but now i am adding next and previous button in it. Whenever next button will be clicked then next reycler items'data should be shown and same with previous button.
But i am getting error in this. It is my code.
RecylerAdapter:
public class ContentViewRecyclerAdapter extends RecyclerView.Adapter<ContentViewRecyclerAdapter.ViewHolder>{
ArrayList<ContentModel>contentModels;
Context context;
public ContentViewRecyclerAdapter(ArrayList<ContentModel> contentModels, Context context) {
this.contentModels = contentModels;
this.context = context;
}
#NonNull
#Override
public ContentViewRecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ContentViewRecyclerAdapter.ViewHolder holder, final int position) {
holder.textView.setText(contentModels.get(position).getContent());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ContentViewActivity.class);
i.putExtra("valuecontent", contentModels.get(position).getContent());
i.putExtra("position", position);
i.putParcelableArrayListExtra("contentmodels", contentModels);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return contentModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.contentText);
}
}
}
ModelClass:
public class ContentModel implements Parcelable {
String content;
public ContentModel(String content) {
this.content = content;
}
protected ContentModel(Parcel in) {
content = in.readString();
}
public static final Creator<ContentModel> CREATOR = new Creator<ContentModel>() {
#Override
public ContentModel createFromParcel(Parcel in) {
return new ContentModel(in);
}
#Override
public ContentModel[] newArray(int size) {
return new ContentModel[size];
}
};
public String getContent() {
return content;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(content);
}
}
ContentViewActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_view);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView_content);
next = findViewById(R.id.next);
prev = findViewById(R.id.prev);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.backbtncntent);
sharebtn = findViewById(R.id.sharebtn);
copybtn = findViewById(R.id.copy);
contentModels = new ArrayList<>();
contentModels.clear();
contentModels = getIntent().getParcelableArrayListExtra("contentmodels");
final String valuecontent = getIntent().getStringExtra("valuecontent");
position = getIntent().getIntExtra("position",0);
textView.setText((Integer) contentModels.get(position));
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ContentViewActivity.this, HomeActivity.class);
startActivity(i);
}
});
sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hey Read Some Interesting Content");
intent.putExtra(android.content.Intent.EXTRA_TEXT, valuecontent);
startActivity(Intent.createChooser(intent, "Share Via"));
}
});
copybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setClipboard(ContentViewActivity.this,textView.getText().toString());
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position =(position+1)%contentModels.size();
textView.setText((Integer) contentModels.get(position));
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position =(position-1)%contentModels.size();
textView.setText((Integer) contentModels.get(position));
}
});
}
private void setClipboard(Context context, String text) {
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
Toast.makeText(ContentViewActivity.this, "Copied to Clipboard", Toast.LENGTH_SHORT).show();
clipboard.setPrimaryClip(clip);
}
}
}
The error i am getting:
Caused by: java.lang.ClassCastException: example.example1.shayariapp.Models.ContentModel cannot be cast to java.lang.Integer
at example.example1.shayariapp.Acitivties.ContentViewActivity.onCreate(ContentViewActivity.java:54)
at android.app.Activity.performCreate(Activity.java:7227)
at android.app.Activity.performCreate(Activity.java:7218)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2941)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3066) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:202) 
at android.app.ActivityThread.main(ActivityThread.java:6962) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888) 
Please please help me to solve this issue. Please
It is located here:
textView.setText((Integer) contentModels.get(position));
You are trying to parse ContentModel item into Integer.
You are doing this 3 times. Inside onCreate() and inside ClickListeners for next and prev.

PostAdapter returning incorrect postids for posts

Introduced some code that makes my PostAdapter return the wrong postid when I Log it, and the post isn't being liked... I am not sure how to fix it. App doesn't crash or anything, but I am unsure how to fix it.
Post has three ImageViews, and when they are clicked on they change color. That before was happening as it is supposed to, but now it isn't working... App doesn't crash, like I said, but when I Log it, I get back the wrong postid.
Likes aren't being saved to correct posts, and comments aren't being recorded.
Can anyone advise me on why this is happening?
PostAdapter
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public Context mContext;
public List<Post> mPost;
public Post post;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPost) {
this.mContext = mContext;
this.mPost = mPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, parent, false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
post = mPost.get(position);
Glide.with(mContext).load(post.getPostimage())
.apply(new RequestOptions().placeholder(R.drawable.placeholderimg))
.into(holder.post_image);
if ("".equals(post.getDescription())) {
holder.description.setVisibility(View.GONE);
} else {
holder.description.setVisibility(View.VISIBLE);
holder.description.setText(post.getDescription());
}
//Timestamp holder
if ("".equals(post.getTimestamp())) {
holder.timestamp.setVisibility(View.GONE);
} else {
holder.timestamp.setVisibility(View.VISIBLE);
String timestampDifference = getTimeDate();
if (!timestampDifference.equals("0")) {
holder.timestamp.setText(timestampDifference + " days ago");
} else {
holder.timestamp.setText("Today");
}
}
if ("".equals(post.getText_event())) {
holder.text_event.setVisibility(View.GONE);
} else {
holder.text_event.setVisibility(View.VISIBLE);
holder.text_event.setText(post.getText_event());
}
if ("".equals(post.getText_location())) {
holder.text_location.setVisibility(View.GONE);
} else {
holder.text_location.setVisibility(View.VISIBLE);
holder.text_location.setText(post.getText_location());
}
if ("".equals(post.getText_date_time())) {
holder.text_date_time.setVisibility(View.GONE);
} else {
holder.text_date_time.setVisibility(View.VISIBLE);
holder.text_date_time.setText(post.getText_date_time());
}
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid())
.child(firebaseUser.getUid()).setValue(true);
addNotification(post.getPublisher(), post.getPostid());
} else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid())
.child(firebaseUser.getUid()).removeValue();
}
}
});
publisherInfo(holder.image_profile, holder.username, post.getPublisher());
attending_event(post.getPostid(), holder.attend_event);
number_of_people_attending_event(holder.number_of_people_attending_event, post.getPostid());
getComments(post.getPostid(), holder.number_of_comments);
getTimeDate();
isSaved(post.getPostid(), holder.save_event);
eventLiked(post.getPostid(), holder.like);
number_of_likes(holder.number_of_likes, post.getPostid());
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("profileid", post.getPublisher());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("profileid", post.getPublisher());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("postid", post.getPostid());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PostDetailFragment()).commit();
}
});
holder.save_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.save_event.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid())
.child(post.getPostid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid())
.child(post.getPostid()).removeValue();
}
}
});
//Setting ViewHolder for the attend_event icon (black)
holder.attend_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("POSTID", post.getPostid());
if (holder.attend_event.getTag().equals("attend event")) {
FirebaseDatabase.getInstance().getReference().child("Attending Event").child(post.getPostid())
.child(firebaseUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Attending Event").child(post.getPostid())
.child(firebaseUser.getUid()).removeValue();
}
}
});
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CommentsActivity.class);
intent.putExtra("postid", post.getPostid());
intent.putExtra("publisherid", post.getPublisher());
mContext.startActivity(intent);
}
});
holder.number_of_comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CommentsActivity.class);
intent.putExtra("postid", post.getPostid());
intent.putExtra("publisherid", post.getPublisher());
mContext.startActivity(intent);
}
});
holder.number_of_likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, FollowersActivity.class);
intent.putExtra("id", post.getPostid());
intent.putExtra("title", "Likes");
mContext.startActivity(intent);
}
});
holder.more_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(mContext, v);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.edit_event:
editPost(post.getPostid());
return true;
case R.id.delete_event:
FirebaseDatabase.getInstance().getReference("Posts").child(post.getPostid()).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(mContext, "Event deleted", Toast.LENGTH_SHORT).show();
}
}
});
return true;
case R.id.report_event:
Toast.makeText(mContext, "Event has been reported", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
popupMenu.inflate(R.menu.event_menu);
if (!post.getPublisher().equals(firebaseUser.getUid())) {
popupMenu.getMenu().findItem(R.id.edit_event).setVisible(false);
popupMenu.getMenu().findItem(R.id.delete_event).setVisible(false);
}
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
if (mPost != null) {
return mPost.size();
} else {
return 0;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, post_image, like, comment, attend_event, save_event, more_options;
public TextView username;
public TextView number_of_likes;
public TextView description;
public TextView number_of_comments;
public TextView text_event;
public TextView text_location;
public TextView text_date_time;
public TextView timestamp;
public TextView number_of_people_attending_event;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile = itemView.findViewById(R.id.image_profile);
post_image = itemView.findViewById(R.id.post_image);
like = itemView.findViewById(R.id.like);
comment = itemView.findViewById(R.id.comment);
username = itemView.findViewById(R.id.username);
number_of_likes = itemView.findViewById(R.id.number_of_likes);
description = itemView.findViewById(R.id.description);
number_of_comments = itemView.findViewById(R.id.number_of_comments);
text_event = itemView.findViewById(R.id.text_event);
text_location = itemView.findViewById(R.id.text_location);
text_date_time = itemView.findViewById(R.id.text_date_time);
attend_event = itemView.findViewById(R.id.attend_event);
number_of_people_attending_event = itemView.findViewById(R.id.number_of_people_attending_event);
save_event = itemView.findViewById(R.id.save_event);
more_options = itemView.findViewById(R.id.more_options);
timestamp = itemView.findViewById(R.id.timestamp);
text_location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MapsActivityUser.class);
intent.putExtra("postid", mPost.get(getAdapterPosition()).getPostid());
intent.putExtra("text_event", mPost.get(getAdapterPosition()).getText_event());
intent.putExtra("text_location", mPost.get(getAdapterPosition()).getText_location());
intent.putExtra("text_date_time", mPost.get(getAdapterPosition()).getText_date_time());
mContext.startActivity(intent);
}
});
}
}
private void eventLiked(String postid, final ImageView imageView) {
if (postid != null) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(firebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_event_liked_aqua_fill);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_favorite_heart_hollow);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void isSaved(final String postid, final ImageView imageView) {
if (firebaseUser.getUid() != null) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (postid != null) {
if (dataSnapshot.child(postid).exists()) {
imageView.setImageResource(R.drawable.ic_bookmark_darker_version);
imageView.setTag("saved");
} else {
imageView.setImageResource(R.drawable.ic_save_hollow);
imageView.setTag("save");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
The problem is at
public Post post;
Whenever a row is rendered, its value is assigned to this one. When the user taps on another row, the adapter still uses this post to get the id.
Just simply get rid of the post and use position to access the item the user just tapped on.
This is because you are using setting a click listener in onbind which will overwrite the previous click listener so the post in that click listener will never be synced up correctly. You should move your click listeners to the viewholder instead. Or an easy fix is to use getItem(viewholder.adapterPosition) in the click listener

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.

Categories

Resources