i create a MediaPlayer on adapter , when user click image it start.
public class ViewHolder extends RecyclerView.ViewHolder {
RoundedImageView imageView;
TextView username;
ImageButton buttonInfo;
public ViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.itemCardStackView);
username = itemView.findViewById(R.id.textViewUsername_stackView);
buttonInfo = itemView.findViewById(R.id.buttonToInfo_stackView);
}
void setData(Users data) {
mediaPlayer = new MediaPlayer();
if (!data.getAudioIntro().equals("")) {
try {
mediaPlayer.setDataSource(data.getAudioIntro());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "no voiceintro", Toast.LENGTH_SHORT).show();
}
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogPreviewInfo dialogPreviewInfo = new DialogPreviewInfo();
Bundle bundle = new Bundle();
bundle.putString("uid", data.getMyUid());
dialogPreviewInfo.setArguments(bundle);
dialogPreviewInfo.show(((FragmentActivity) context).getSupportFragmentManager(), "tag");
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!data.getAudioIntro().equals("")) {
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
else {
mediaPlayer.start();
}
}
}
});
}
it work,but i want when user swiped imageView , it stop and release MediaPlayer.i know how to use interface pass data from adapter to acivity,but opposite , i don't.
This is my code on activity for CardStackView
manager = new CardStackLayoutManager(getContext(), new CardStackListener() {
#Override
public void onCardDragging(Direction direction, float ratio) {
}
#Override
public void onCardSwiped(Direction direction) {
Log.d(TAG, "onCardSwiped: p=" + manager.getTopPosition() + " d=" + direction);
if (direction == Direction.Right) {
Toast.makeText(getContext(), "Direction Right", Toast.LENGTH_SHORT).show();
}
if (direction == Direction.Top) {
Toast.makeText(getContext(), "Direction Top", Toast.LENGTH_SHORT).show();
}
if (direction == Direction.Left) {
Toast.makeText(getContext(), "Direction Left", Toast.LENGTH_SHORT).show();
}
if (direction == Direction.Bottom) {
Toast.makeText(getContext(), "Direction Bottom", Toast.LENGTH_SHORT).show();
}
if (manager.getTopPosition() == adapter.getItemCount() - 5){
paginate();
}
}
#Override
public void onCardRewound() {
Log.d(TAG, "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardCanceled() {
Log.d(TAG, "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardAppeared(View view, int position) {
Log.d(TAG, "onCardAppeared: " + position);
}
#Override
public void onCardDisappeared(View view, int position) {
Log.d(TAG, "onCardAppeared: " + position);
}
});
manager.setStackFrom(StackFrom.None);
manager.setVisibleCount(3);
manager.setTranslationInterval(20.0f);
manager.setScaleInterval(0.95f);
manager.setSwipeThreshold(0.1f);
manager.setMaxDegree(20.0f);
manager.setDirections(Direction.FREEDOM);
manager.setCanScrollHorizontal(true);
manager.setCanScrollVertical(true);
manager.setSwipeableMethod(SwipeableMethod.AutomaticAndManual);
adapter = new CardStackAdapter(getContext(), listUser, this);
binding.cardStackView.setLayoutManager(manager);
binding.cardStackView.setAdapter(adapter);
binding.cardStackView.setItemAnimator(new DefaultItemAnimator());
can anyone help me , please!
have a nice day,everyone!
Related
Everytime I click on the nextBTn and PrevBtn in "music player activity",the next/previous Items in the recyclerview of "songs activity" or it's adapter need to play the perticuclar song in "Player activity".
I tried to make position++ and position-- but the items need to save in player activity I guess.
How can I play next and previous song when my player activity and adapter are two different activities.
How can I give the recyclerview items of the song currently playing and apply previoussongBTn,nextsongBTn?
code of player.java
public class player extends AppCompatActivity {
private ImageView imagePlayPause, forwardBtn, backwardBtn;
MediaPlayer mediaPlayer;
ImageView songImageIV;
String song_path,image_path,song_name,album_name,sng_path,pre_song;
TextView song_nameTV,albumNameTV;
private SeekBar playerSeekBar;
private TextView textCurrentTime, textTotalDuration;
private Handler handler = new Handler();
AdapterSongs songAdapter;
private int seekForwardTime = 10 * 1000;
private int seekBackwardTime = 10 * 1000; // default 10 second
private ChipNavigationBar chipNavigationBar;//for navigation
TextView scrollingText;//song name which scrolls horizontally
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_activity);
songImageIV = findViewById(R.id.song_image);
song_nameTV = findViewById(R.id.tv_songName);
albumNameTV = findViewById(R.id.topBarAlbumName);
textCurrentTime = findViewById(R.id.current_time);
textTotalDuration = findViewById(R.id.totalDuration);
playerSeekBar = findViewById(R.id.seekbar);
imagePlayPause = findViewById(R.id.playbtn);
forwardBtn = findViewById(R.id.forwardBtn);
backwardBtn = findViewById(R.id.backwardBtn);
mediaPlayer = playerInstance.getInstance();
playerSeekBar.setMax(100);
SharedPreferences sharedPreferences = getSharedPreferences("songDetails",MODE_PRIVATE);
song_path = sharedPreferences.getString("songPath","");
image_path = sharedPreferences.getString("album_img","");
song_name = sharedPreferences.getString("songName","");
album_name = sharedPreferences.getString("album_name","");
pre_song = sharedPreferences.getString("pre_song","");
// albumNameTV.append(album_name);
Picasso.get().load(image_path).into(songImageIV);
song_nameTV.setText(song_name);
albumNameTV.append(album_name);
scrollingText = (TextView)findViewById(R.id.tv_songName);
scrollingText.setSelected(true);
Log.i("tagconvertstr", "[song_path = " +song_path + "]");
Log.i("tagconvertstr", "[pre_path" + pre_song + "]");
if(!song_path.equals(pre_song))
{
prepareMediaPlayer();
textTotalDuration.setText(milisecToTimer(mediaPlayer.getDuration()));
if(!mediaPlayer.isPlaying()){
prepareMediaPlayer();
}
}
if(mediaPlayer.isPlaying())
{
imagePlayPause.setImageResource(R.drawable.pause_icon);
updater.run();
textTotalDuration.setText(milisecToTimer(mediaPlayer.getDuration()));
}
if(song_path.equalsIgnoreCase(pre_song))
{
updater.run();
textTotalDuration.setText(milisecToTimer(mediaPlayer.getDuration()));
}
navigation();//for navigation
imagePlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playpause();
}
});
playerSeekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
SeekBar seekBar = (SeekBar) view;
int playPosition = (mediaPlayer.getDuration()/100)*seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
textCurrentTime.setText(milisecToTimer(mediaPlayer.getCurrentPosition()));
return false;
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
playerSeekBar.setSecondaryProgress(i);
}
});
if(mediaPlayer!=null) {
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.reset();
prepareMediaPlayer();
playerSeekBar.setProgress(0);
imagePlayPause.setImageResource(R.drawable.pause_icon);
textCurrentTime.setText(R.string.zero);
textTotalDuration.setText(R.string.zero);
}
});
}
forwardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forwardSong();
}
});
backwardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rewindSong();
}
});
}
public void forwardSong() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition();
if (currentPosition + seekForwardTime <= mediaPlayer.getDuration()) {
mediaPlayer.seekTo(currentPosition + seekForwardTime);
} else {
mediaPlayer.seekTo(mediaPlayer.getDuration());
}
}
}
public void rewindSong() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition();
if (currentPosition - seekBackwardTime >= 0) {
mediaPlayer.seekTo(currentPosition - seekBackwardTime);
} else {
mediaPlayer.seekTo(0);
}
}
}
private void prepareMediaPlayer(){
mediaPlayer.reset();
pre_song = song_path;
SharedPreferences sharedPreferences = getSharedPreferences("songDetails",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("pre_song",pre_song);
editor.apply();
imagePlayPause.setImageResource(R.drawable.pause_icon);
try{
mediaPlayer.setDataSource(song_path);
// mediaPlayer.setDataSource("https://testing-ariya.s3.ap-south-1.amazonaws.com/Faded_320(PaglaSongs).mp3");
mediaPlayer.prepare();
textTotalDuration.setText(milisecToTimer(mediaPlayer.getDuration()));
mediaPlayer.start();
updater.run();
}catch (Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public Runnable updater = new Runnable() {
#Override
public void run() {
updateseekbar();
long currentDuration = mediaPlayer.getCurrentPosition();
textCurrentTime.setText(milisecToTimer(currentDuration));
}
};
public void updateseekbar(){
if(mediaPlayer.isPlaying()){
playerSeekBar.setProgress((int) (((float) mediaPlayer.getCurrentPosition()/mediaPlayer.getDuration()) *100));
handler.postDelayed(updater,1000);
}
}
private String milisecToTimer(long milliseconds){
String timerString= "";
String secondsString;
int hours = (int) (milliseconds/(1000*60*60));
int minutes = (int) (milliseconds % (1000*60*60))/ (1000*60);
int seconds = (int) ((milliseconds%(1000*60*60))%(1000*60)/1000);
if (hours > 0) {
timerString = hours + ":";
}
if (seconds<10){
secondsString = "0" +seconds;
}else{
secondsString = ""+seconds;
}
timerString = timerString+minutes+":"+secondsString;
return timerString;
}
public void navigation() {
chipNavigationBar = findViewById(R.id.chipNavigation);
chipNavigationBar.setItemSelected(R.id.player, true);
//getSupportFragmentManager().beginTransaction().replace(R.id.container, new HomeFragment()).commit();
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
#Override
public void onItemSelected(int i) {
switch (i) {
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0, 0);
finish();
return ;
case R.id.player:
return ;
}
}
});
}
public void playpause()
{
if(mediaPlayer.isPlaying()){
handler.removeCallbacks(updater);
mediaPlayer.pause();
imagePlayPause.setImageResource(R.drawable.play_icon);
}else{
imagePlayPause.setImageResource(R.drawable.pause_icon);
mediaPlayer.start();
updateseekbar();
}
}
}
code of Adaptersongs.java
public class AdapterSongs extends RecyclerView.Adapter<AdapterSongs.ViewHolder2>{
public List<SongsModelClass> songsModelClassList;
Context context;
Dialog customDialog;
public int selectedPosition;//for next and prev song playing
public AdapterSongs(List<SongsModelClass> songsModelClassList, Context context) {
super();
this.songsModelClassList = songsModelClassList;
this.context = context;
}
#NonNull
#Override
public ViewHolder2 onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_song_row,parent,false);
ViewHolder2 viewHolder2 = new ViewHolder2(view);
return viewHolder2;
}
#Override
public void onBindViewHolder(#NonNull AdapterSongs.ViewHolder2 holder2, int position) {
SongsModelClass songData = songsModelClassList.get(position);
holder2.title.setText(songData.getTitle());
//Picasso.get().load(albumdata.getArtworkPath()).into(holder2.thumbnail);
holder2.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPreferences1 = context.getSharedPreferences("login",Context.MODE_PRIVATE);
String userType = sharedPreferences1.getString("subscription","");
Log.i("tagconvertstr", "[userType" + userType + "]");
if(songData.getSongType().equalsIgnoreCase("YES")&&userType.equalsIgnoreCase("NO"))
{
customDialog = new Dialog(context);
customDialog.setContentView(R.layout.premium_alert_box);
customDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.setCancelable(false);
customDialog.show();
TextView cancel = customDialog.findViewById(R.id.changeEmail);
TextView subscribe = customDialog.findViewById(R.id.confirmEmail);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context,PremiumScreen.class);
context.startActivity(i);
customDialog.dismiss();
}
});
return;
}
Log.i("tagconvertstr", "[" + songData.getPath() + "]");
Intent intent = new Intent(context,player.class);
intent.putExtra("song_name",songData.getTitle());
intent.putExtra("song_path",songData.getPath());
intent.putExtra("album_img",songData.getArtworkPath());
intent.putExtra("album_name",songData.getSongAlbum());
SharedPreferences sharedPreferences = context.getSharedPreferences("songDetails",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("songPath",songData.getPath());
editor.putString("songName",songData.getTitle());
editor.putString("album_img",songData.getArtworkPath());
editor.putString("album_name",songData.getSongAlbum());
editor.apply();
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return songsModelClassList.size();
}
class ViewHolder2 extends RecyclerView.ViewHolder{
// ImageView thumbnail;
TextView title;
TextView id;
public ViewHolder2(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.song_title);
}
}
}
I'm trying to filter posts types (for example only images, audio, videos.....) and change the adapter to update items inside recycler view. But for some reason the first time i make any changes to my filter dialog the feature works without problems, but if i try to make any changes for 2nd time inside my dialog, i'm getting an java.lang.ClassCastException.
Error:
java.lang.ClassCastException: com.george.socialmeme.ViewHolders.ImageItemViewHolder cannot be cast to com.george.socialmeme.ViewHolders.VideoItemViewHolder
Method that displays the filter dialog:
void showFiltersDialog() {
Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.posts_filter_bottom_sheet);
View imagesItem = dialog.findViewById(R.id.view23);
View videosItem = dialog.findViewById(R.id.view21);
View soundsItem = dialog.findViewById(R.id.view22);
View textItem = dialog.findViewById(R.id.view20);
Button applyFiltersBtn = dialog.findViewById(R.id.apply_filters);
if (!imagesItemSelected[0]) {
dialog.findViewById(R.id.imageView30).setVisibility(View.GONE);
}
if (!videosItemSelected[0]) {
dialog.findViewById(R.id.imageView32).setVisibility(View.GONE);
}
if (!soundsItemSelected[0]) {
dialog.findViewById(R.id.imageView34).setVisibility(View.GONE);
}
if (!textItemSelected[0]) {
dialog.findViewById(R.id.imageView36).setVisibility(View.GONE);
}
imagesItem.setOnClickListener(view -> {
if (imagesItemSelected[0]) {
imagesItemSelected[0] = false;
dialog.findViewById(R.id.imageView30).setVisibility(View.GONE);
} else {
imagesItemSelected[0] = true;
dialog.findViewById(R.id.imageView30).setVisibility(View.VISIBLE);
}
});
videosItem.setOnClickListener(view -> {
if (videosItemSelected[0]) {
videosItemSelected[0] = false;
dialog.findViewById(R.id.imageView32).setVisibility(View.GONE);
} else {
videosItemSelected[0] = true;
dialog.findViewById(R.id.imageView32).setVisibility(View.VISIBLE);
}
});
soundsItem.setOnClickListener(view -> {
if (soundsItemSelected[0]) {
soundsItemSelected[0] = false;
dialog.findViewById(R.id.imageView34).setVisibility(View.GONE);
} else {
soundsItemSelected[0] = true;
dialog.findViewById(R.id.imageView34).setVisibility(View.VISIBLE);
}
});
textItem.setOnClickListener(view -> {
if (textItemSelected[0]) {
textItemSelected[0] = false;
dialog.findViewById(R.id.imageView36).setVisibility(View.GONE);
} else {
textItemSelected[0] = true;
dialog.findViewById(R.id.imageView36).setVisibility(View.VISIBLE);
}
});
applyFiltersBtn.setOnClickListener(view -> {
filteredPostsArrayList.clear();
applyFiltersBtn.setText("Filtering...");
applyFiltersBtn.setEnabled(false);
dialog.setCancelable(false);
for (PostModel postModel : postModelArrayList) {
if (postModel.getPostType().equals("image")) {
if (imagesItemSelected[0]) {
filteredPostsArrayList.add(postModel);
}
}
if (postModel.getPostType().equals("video")) {
if (videosItemSelected[0]) {
filteredPostsArrayList.add(postModel);
}
}
if (postModel.getPostType().equals("audio")) {
if (soundsItemSelected[0]) {
filteredPostsArrayList.add(postModel);
}
}
if (postModel.getPostType().equals("text")) {
if (textItemSelected[0]) {
filteredPostsArrayList.add(postModel);
}
}
}
// Update RecyclerView adapter
recyclerAdapter = new PostRecyclerAdapter(filteredPostsArrayList, getContext(), getActivity());
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setStackFromEnd(true);
layoutManager.setReverseLayout(true);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setLayoutManager(layoutManager);
// Add post's of the month view as RecyclerView item
// to avoid using ScrollView
PostModel postsOfTheMonthView = new PostModel();
postsOfTheMonthView.setPostType("postsOfTheMonth");
filteredPostsArrayList.add(postsOfTheMonthView);
recyclerAdapter.notifyDataSetChanged();
dialog.dismiss();
});
dialog.show();
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(android.view.Gravity.BOTTOM);
}
My PostRecyclerAdapter class:
public class PostRecyclerAdapter extends RecyclerView.Adapter {
List<PostModel> postList;
Context context;
Activity activity;
#Override
public int getItemViewType(int position) {
if (postList.get(position).getPostType().equals("video")) {
return 1;
}
if (postList.get(position).getPostType().equals("postsOfTheMonth")) {
return 2;
}
if (postList.get(position).getPostType().equals("audio")) {
return 3;
}
if (postList.get(position).getPostType().equals("text")) {
return 4;
}
return 0;
}
public PostRecyclerAdapter(ArrayList<PostModel> postModelArrayList, Context context, Activity activity) {
this.postList = postModelArrayList;
this.context = context;
this.activity = activity;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == 1) {
return new VideoItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.video_post_item, parent, false));
}
if (viewType == 2) {
return new PostsOfTheMonthItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.posts_of_the_month_view_item, parent, false));
}
if (viewType == 3) {
return new AudioItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.audio_post_item, parent, false));
}
if (viewType == 4) {
return new PostTextItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.text_post_item, parent, false));
}
return new ImageItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.image_post_item, parent, false));
}
// Release ExoPlayer when a video item is recycled
// to avoid player errors on other video items inside RecyclerView
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if (postList.get(holder.getLayoutPosition()).getPostType().equals("video")) {
VideoItemViewHolder videoViewHolder = (VideoItemViewHolder) holder;
videoViewHolder.andExoPlayerView.getPlayer().release();
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
DatabaseReference likeRef = FirebaseDatabase.getInstance().getReference("likes");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
if (postList.get(position).getPostType().equals("postsOfTheMonth")) {
PostsOfTheMonthItemViewHolder viewHolder = (PostsOfTheMonthItemViewHolder) holder;
viewHolder.setContext(context);
}
if (postList.get(position).getPostType().equals("text")) {
// Bind audio view holder
PostTextItemViewHolder textItemViewHolder = (PostTextItemViewHolder) holder;
textItemViewHolder.setContext(context);
if (HomeActivity.singedInAnonymously) {
textItemViewHolder.commentsCount.setVisibility(View.GONE);
textItemViewHolder.postOptionsButton.setVisibility(View.GONE);
textItemViewHolder.openCommentsView.setVisibility(View.GONE);
textItemViewHolder.shareBtn.setVisibility(View.GONE);
}else {
if (user.getUid().equals(postList.get(position).getAuthorID())) {
textItemViewHolder.followBtnView.setVisibility(View.GONE);
}
}
// check if post is liked or not
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (!HomeActivity.singedInAnonymously) {
// check if current post is liked from this user
if (snapshot.child(textItemViewHolder.postID).hasChild(user.getUid())) {
// post is liked form this user
textItemViewHolder.like_btn.setImageResource(R.drawable.ic_like_filled);
textItemViewHolder.isPostLiked = true;
} else {
// post is not liked from this user
textItemViewHolder.like_btn.setImageResource(R.drawable.ic_like);
textItemViewHolder.isPostLiked = false;
}
} else {
textItemViewHolder.like_btn.setEnabled(false);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
textItemViewHolder.postID = postList.get(position).getId();
textItemViewHolder.username.setText(postList.get(position).getName());
textItemViewHolder.postAuthorID = postList.get(position).getAuthorID();
textItemViewHolder.like_counter_tv.setText(postList.get(position).getLikes());
textItemViewHolder.commentsCount.setText(postList.get(position).getCommentsCount());
// Load Title and content for the post
textItemViewHolder.postTitle.setText(postList.get(position).getPostTitle());
textItemViewHolder.postContentText.setText(postList.get(position).getPostContentText());
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(textItemViewHolder.profilePicture);
}
}
textItemViewHolder.shareBtn.setOnClickListener(view -> {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post_url", postList.get(position).getImgUrl());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Audio URL copied to clipboard", Toast.LENGTH_SHORT).show();
});
}
if (postList.get(position).getPostType().equals("audio")) {
// Bind audio view holder
AudioItemViewHolder audioViewHolder = (AudioItemViewHolder) holder;
audioViewHolder.setContext(context);
if (HomeActivity.singedInAnonymously) {
audioViewHolder.commentsCounter.setVisibility(View.GONE);
audioViewHolder.postOptionsBtn.setVisibility(View.GONE);
audioViewHolder.openCommentsView.setVisibility(View.GONE);
audioViewHolder.shareBtn.setVisibility(View.GONE);
}else {
if (user.getUid().equals(postList.get(position).getAuthorID())) {
audioViewHolder.followBtnView.setVisibility(View.GONE);
}
}
// check if post is liked or not
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (!HomeActivity.singedInAnonymously) {
// check if current post is liked from this user
if (snapshot.child(audioViewHolder.postID).hasChild(user.getUid())) {
// post is liked form this user
audioViewHolder.likeBtn.setImageResource(R.drawable.ic_like_filled);
audioViewHolder.isPostLiked = true;
} else {
// post is not liked from this user
audioViewHolder.likeBtn.setImageResource(R.drawable.ic_like);
audioViewHolder.isPostLiked = false;
}
} else {
// disable like button
audioViewHolder.likeBtn.setEnabled(false);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
audioViewHolder.postID = postList.get(position).getId();
audioViewHolder.usernameTV.setText(postList.get(position).getName());
audioViewHolder.postAuthorID = postList.get(position).getAuthorID();
audioViewHolder.likesCounter.setText(postList.get(position).getLikes());
audioViewHolder.audioURL = postList.get(position).getImgUrl();
audioViewHolder.audioName.setText(postList.get(position).getAudioName());
audioViewHolder.commentsCounter.setText(postList.get(position).getCommentsCount());
// Load audio source
audioViewHolder.audioPlayerView.withUrl(postList.get(position).getImgUrl());
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(audioViewHolder.profilePicture);
}
}
audioViewHolder.shareBtn.setOnClickListener(view -> {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post_url", postList.get(position).getImgUrl());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Audio URL copied to clipboard", Toast.LENGTH_SHORT).show();
});
}
if (postList.get(position).getPostType().equals("video")) {
// bind video view holder
VideoItemViewHolder videoViewHolder = (VideoItemViewHolder) holder;
videoViewHolder.setContext(context);
if (HomeActivity.singedInAnonymously) {
videoViewHolder.commentsCount.setVisibility(View.GONE);
videoViewHolder.postOptionsButton.setVisibility(View.GONE);
videoViewHolder.commentsBtn.setVisibility(View.GONE);
videoViewHolder.shareBtn.setVisibility(View.GONE);
}else {
if (user.getUid().equals(postList.get(position).getAuthorID())) {
videoViewHolder.followBtnView.setVisibility(View.GONE);
}
}
// check if post is liked or not
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (!HomeActivity.singedInAnonymously) {
// check if current post is liked from this user
if (snapshot.child(videoViewHolder.postID).hasChild(user.getUid())) {
// post is liked form this user
videoViewHolder.like_btn.setImageResource(R.drawable.ic_like_filled);
videoViewHolder.isPostLiked = true;
} else {
// post is not liked from this user
videoViewHolder.isPostLiked = false;
videoViewHolder.like_btn.setImageResource(R.drawable.ic_like);
}
} else {
// disable like button
videoViewHolder.like_btn.setEnabled(false);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "error: " + error, Toast.LENGTH_SHORT).show();
}
});
videoViewHolder.postID = postList.get(position).getId();
videoViewHolder.username.setText(postList.get(position).getName());
videoViewHolder.postAuthorID = postList.get(position).getAuthorID();
videoViewHolder.like_counter_tv.setText(postList.get(position).getLikes());
videoViewHolder.videoURL = postList.get(position).getImgUrl();
videoViewHolder.commentsCount.setText(postList.get(position).getCommentsCount());
// Load video source
ExoPlayer player = new ExoPlayer.Builder(context).build();
MediaItem mediaItem = MediaItem.fromUri(postList.get(position).getImgUrl());
player.setMediaItem(mediaItem);
player.prepare();
videoViewHolder.andExoPlayerView.setPlayer(player);
player.addAnalyticsListener(new AnalyticsListener() {
#Override
public void onPlayerError(#NonNull EventTime eventTime, #NonNull PlaybackException error) {
//Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
Log.i("EXOPLAYER_ERROR", "" + error.getMessage());
}
});
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(videoViewHolder.profilePicture);
}
}
videoViewHolder.shareBtn.setOnClickListener(view -> {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post_url", postList.get(position).getImgUrl());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Video URL copied to clipboard", Toast.LENGTH_SHORT).show();
});
}
if (postList.get(position).getPostType().equals("image")) {
// bind image view holder
ImageItemViewHolder imageViewHolder = (ImageItemViewHolder) holder;
imageViewHolder.setContext(context);
if (HomeActivity.singedInAnonymously) {
imageViewHolder.commentsCount.setVisibility(View.GONE);
imageViewHolder.show_comments_btn.setVisibility(View.GONE);
imageViewHolder.showPostOptionsButton.setVisibility(View.GONE);
imageViewHolder.shareBtn.setVisibility(View.GONE);
}else {
if (user.getUid().equals(postList.get(position).getAuthorID())) {
imageViewHolder.followBtnView.setVisibility(View.GONE);
}
}
// check if post is liked or not from the user
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (!HomeActivity.singedInAnonymously) {
// check if current post is liked from this user
if (snapshot.child(imageViewHolder.postID).hasChild(user.getUid())) {
// post is liked form this user
imageViewHolder.like_btn.setImageResource(R.drawable.ic_like_filled);
imageViewHolder.isPostLiked = true;
} else {
// post is not liked from this user
imageViewHolder.isPostLiked = false;
imageViewHolder.like_btn.setImageResource(R.drawable.ic_like);
}
} else {
imageViewHolder.like_btn.setEnabled(false);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "error: " + error, Toast.LENGTH_SHORT).show();
}
});
imageViewHolder.postID = postList.get(position).getId();
imageViewHolder.username.setText(postList.get(position).getName());
imageViewHolder.postAuthorID = postList.get(position).getAuthorID();
imageViewHolder.like_counter_tv.setText(postList.get(position).getLikes());
imageViewHolder.commentsCount.setText(postList.get(position).getCommentsCount());
Picasso.get().load(postList.get(position).getImgUrl()).into(imageViewHolder.postImg, new Callback() {
#Override
public void onSuccess() {
imageViewHolder.loadingProgressBar.setVisibility(View.GONE);
}
#Override
public void onError(Exception e) {
Toast.makeText(context, "Can't load this image: " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
imageViewHolder.postImageURL = postList.get(position).getImgUrl();
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(imageViewHolder.profileImage);
}
}
imageViewHolder.shareBtn.setOnClickListener(view -> {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post_url", postList.get(position).getImgUrl());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Image URL copied to clipboard", Toast.LENGTH_SHORT).show();
});
}
}
#Override
public int getItemCount() {
return postList.size();
}
}
It seems you're trying to cast item which is not an instance of VideoItemViewHolder to VideoItemViewHolder. Before making cast, check if the item is an instance of VideoItemViewHolder:
if(holder instanceof VideoItemViewHolder){
VideoItemViewHolder videoViewHolder = (VideoItemViewHolder) holder;
//Do your stuff...
} else {
//Cast cannot be done
}
public class userListActivity extends AppCompatActivity {
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getPhoto();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.share_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.share) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
getPhoto();
}
} else if (item.getItemId() == R.id.logout) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
setTitle("User Feed");
final ListView listView = findViewById(R.id.listView);
final ArrayList<String> usernames = new ArrayList<String>();
final ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, usernames);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), userFeedActivity.class);
intent.putExtra("username", usernames.get(i));
startActivity(intent);
}
});
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("username",ParseUser.getCurrentUser().getUsername());
query.addAscendingOrder("username");
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseUser user : objects) {
usernames.add(user.getUsername());
}
listView.setAdapter(arrayAdapter);
}
} else {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = data.getData();
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
Log.i("Image Selected", "Good work");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
ParseFile file = new ParseFile("image.png", byteArray);
ParseObject object = new ParseObject("Image");
object.put("image", file);
object.put("username", ParseUser.getCurrentUser().getUsername());
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(userListActivity.this, "Image has been shared!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(userListActivity.this, "There has been an issue uploading the image :(", Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnKeyListener {
Boolean signUpModeActive = true;
TextView loginTextView;
EditText usernameEditText;
EditText passwordEditText;
public void showUserList() {
Intent intent = new Intent(getApplicationContext(), userListActivity.class);
startActivity(intent);
}
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
signUpClicked(view);
}
return false;
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.loginTextView) {
Button signUpButton = findViewById(R.id.signUpButton);
if (signUpModeActive) {
signUpModeActive = false;
signUpButton.setText("Login");
loginTextView.setText("or, Sign Up");
} else {
signUpModeActive = true;
signUpButton.setText("Sign Up");
loginTextView.setText("or, Login");
}
} else if (view.getId() == R.id.logoimageView || view.getId() == R.id.backgroudLayout) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
}
}
public void signUpClicked(View view) {
if (usernameEditText.getText().toString().matches("") || passwordEditText.getText().toString().matches("")) {
Toast.makeText(this, "A username and a password are required.",Toast.LENGTH_SHORT).show();
} else {
if (signUpModeActive) {
ParseUser user = new ParseUser();
user.setUsername(usernameEditText.getText().toString());
user.setPassword(passwordEditText.getText().toString());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("Signup", "Success");
showUserList();
} else {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
// Login
ParseUser.logInInBackground(usernameEditText.getText().toString(), passwordEditText.getText().toString(), new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (user != null) {
Log.i("Login","ok!");
showUserList();
} else {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Instagram");
loginTextView = findViewById(R.id.loginTextView);
loginTextView.setOnClickListener(this);
usernameEditText = findViewById(R.id.usernameEditText);
passwordEditText = findViewById(R.id.passwordEditText);
ImageView logoImageView = findViewById(R.id.logoimageView);
ConstraintLayout backgroundLayout = findViewById(R.id.backgroudLayout);
logoImageView.setOnClickListener(this);
backgroundLayout.setOnClickListener(this);
passwordEditText.setOnKeyListener(this);
if (ParseUser.getCurrentUser() != null) {
showUserList();
}
ParseAnalytics.trackAppOpenedInBackground(getIntent());
}
public class userFeedActivity extends AppCompatActivity {
LinearLayout linLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_feed);
Intent intent = getIntent();
String username = intent.getStringExtra("username");
setTitle(username + "'s Photos");
linLayout = findViewById(R.id.linLayout);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Image");
query.whereEqualTo("username", username);
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null && objects.size() > 0) {
for (ParseObject object : objects) {
ParseFile file = (ParseFile) object.get("image");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null && data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
imageView.setImageBitmap(bitmap);
linLayout.addView(imageView);
}
}
});
}
}
}
});
}
I EDITED IT
THIS I MY WHOLE CODE NOW
PLEASE HELP
I want to play 6 different sounds triggered by 6 different buttons in background, so that if the app is on background the sound keeps playing.
When one sound is already playing, pressing another button will stop it and play its own sound,
Tapping the same button 2K times it stops, 2K+1 times: starts again.. (K is a non-null integer)
All of the code is done and seems to be working correctly, except that the player stops after one and a half minute. (This is not because of low memory)
Can anyone please tell me what am I doing wrong?
public class PlayService extends Service {
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
int btnId = intent.getExtras().getInt("ID");
Toast.makeText(this, "onStart service" + btnId, Toast.LENGTH_SHORT).show();
selectResId(btnId);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_SHORT).show();
if (player != null) {
player.stop();
player.release();
}
player = null;
}
#Override
public void onLowMemory() {
super.onLowMemory();
Toast.makeText(this, "Low mem", Toast.LENGTH_SHORT).show();
}
private void selectResId(int resId){
switch (resId){
case 1: playMediaFromResource(R.raw.number_one);
case 2: playMediaFromResource(R.raw.number_two);
case 3: playMediaFromResource(R.raw.number_three);
case 4: playMediaFromResource(R.raw.number_four);
case 5: playMediaFromResource(R.raw.number_five);
case 6: playMediaFromResource(R.raw.number_six);
default: break;
}
}
private void playMediaFromResource(int resId) {
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + resId);
try {
player.setDataSource(getApplicationContext(), mediaPath);
player.setLooping(true);
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the MainActivity:
public class MainActivity extends AppCompatActivity {
private Button btnStart1;
private Button btnStart2;
private Button btnStart3;
private Button btnStart4;
private Button btnStart5;
private Button btnStart6;
private Intent intent;
private int previousID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
setOnClickListeners();
}
private void findViewsByIds() {
btnStart1 = findViewById(R.id.btn_start_1);
btnStart2 = findViewById(R.id.btn_start_2);
btnStart3 = findViewById(R.id.btn_start_3);
btnStart4 = findViewById(R.id.btn_start_4);
btnStart5 = findViewById(R.id.btn_start_5);
btnStart6 = findViewById(R.id.btn_start_6);
}
private void setOnClickListeners() {
btnStart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(1);
}
});
btnStart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(2);
}
});
btnStart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(3);
}
});
btnStart4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(4);
}
});
btnStart5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(5);
}
});
btnStart6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(6);
}
});
}
private void checkIntentState(int ID) {
if (intent == null) {
createNewIntent(ID);
} else {
stopService(intent);
intent = null;
if (ID != previousID) {
createNewIntent(ID);
}
}
}
private void createNewIntent(int ID) {
intent = new Intent(MainActivity.this, PlayService.class);
intent.putExtra("ID", ID);
startService(intent);
previousID = ID;
}
}
I want to answer to my own question just in case anyone else runs into the problem.
It turns out, that Android added some new features (restricted access to background resources for battery life improvement purposes since Oreo(i.e. Android 8.0+ || API level 26)).
As the documentation says:
"Apps that are running in the background now have limits on how freely they can access background services."
So, in this case we will need to use foreground services.
I am trying to run my app using Adapters and I am getting this error while doing that:
Mentioning that there are 3 adapters: ReviewsAdapter, StandupWithKey and VideoAdapter.
05-07 20:16:57.707 5326-5326/com.example.sefi.authenticationproject E/ReviewsAdapter: onBindViewHolder() >> 0
05-07 20:16:57.708 5326-5326/com.example.sefi.authenticationproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sefi.authenticationproject, PID: 5326
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.sefi.authenticationproject.adapter.ReviewsAdapter.onBindViewHolder(ReviewsAdapter.java:48)
at com.example.sefi.authenticationproject.adapter.ReviewsAdapter.onBindViewHolder(ReviewsAdapter.java:18)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3109)
at android.view.View.measure(View.java:19734)
at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1210)
at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1550)
at android.view.View.measure(View.java:19734)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19734)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
at android.view.View.measure(View.java:19734)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:687)
at android.view.View.measure(View.java:19734)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:619)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
And this are my files:
ReviewsAdapter.java
public class ReviewsAdapter extends RecyclerView.Adapter<ReviewsAdapter.ReviewViewHolder> {
private final String TAG = "ReviewsAdapter";
private List<Review> reviewsList;
public ReviewsAdapter(List<Review> reviewsList) {
this.reviewsList = reviewsList;
}
#Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e(TAG,"onCreateViewHolder() >>");
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_standup_details, parent, false);
Log.e(TAG,"onCreateViewHolder() <<");
return new ReviewViewHolder(parent.getContext(),itemView);
}
#Override
public void onBindViewHolder(ReviewViewHolder holder, int position) {
Log.e(TAG,"onBindViewHolder() >> " + position);
Review review = reviewsList.get(position);
holder.getUserMail().setText(review.getUserEmail());
holder.getUserReview().setText(review.getUserReview());
holder.getUserRating().setRating(review.getUserRating());
Log.e(TAG,"onBindViewHolder() << "+ position);
}
#Override
public int getItemCount() {
return reviewsList.size();
}
public class ReviewViewHolder extends RecyclerView.ViewHolder {
private TextView userReview;
private TextView userMail;
private RatingBar userRating;
public ReviewViewHolder(Context context, View view) {
super(view);
userReview = (TextView) view.findViewById(R.id.user_review);
userMail = (TextView) view.findViewById(R.id.user_mail);
userRating = (RatingBar) view.findViewById(R.id.user_rating);
}
public TextView getUserReview() {
return userReview;
}
public void setUserReview(TextView userReview) {
this.userReview = userReview;
}
public TextView getUserMail() {
return userMail;
}
public void setUserMail(TextView userMail) {
this.userMail = userMail;
}
public RatingBar getUserRating() {
return userRating;
}
public void setUserRating(RatingBar userRating) {
this.userRating = userRating;
}
}
}
StandupDetails.java
public class StandupDetails extends Activity {
public final String TAG = "StandupDetails";
private Standup standup;
private String key;
private User user;
private FloatingActionButton writeReview;
private Button buyPlay;
private MediaPlayer mediaPlayer;
private RecyclerView recyclerViewStandupReviews;
private DatabaseReference standupReviewsRef;
private List<Review> reviewsList = new ArrayList<>();
private boolean standupWasPurchased;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_standup_details);
key = getIntent().getStringExtra("key");
standup = getIntent().getParcelableExtra("standup");
user = getIntent().getParcelableExtra("user");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
StorageReference thumbRef = FirebaseStorage
.getInstance()
.getReference()
.child("thumbs/" + standup.getThumbImage());
// Load the image using Glide
thumbRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(StandupDetails.this).load(uri)
.into((ImageView)findViewById(R.id.imageViewSong));
}
});
((TextView) findViewById(R.id.textViewName)).setText(standup.getName());
buyPlay = ((Button) findViewById(R.id.buttonBuyPlay));
buyPlay.setText("BUY $" + standup.getPrice());
Iterator i = user.getMyStandups().iterator();
while (i.hasNext()) {
if (i.next().equals(key)) {
standupWasPurchased = true;
buyPlay.setText("PLAY");
break;
}
}
buyPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG, "buyPlay.onClick() >> file=" + standup.getName());
FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
String info = fbUser.getProviderId();
if (standupWasPurchased) {
Log.e(TAG, "buyPlay.onClick() >> Playing purchased standup");
//User purchased the standup so he can play it
playCurrentStandup(standup.getFile());
}
else{
Log.e(TAG, "buyPlay.onClick() >> Purchase the standup");
user.getMyStandups().add(key);
user.upgdateTotalPurchase(standup.getPrice());
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("Users");
userRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
standupWasPurchased = true;
buyPlay.setText("PLAY");
}
Log.e(TAG, "playStandup.onClick() <<");
}
});
writeReview = (FloatingActionButton) findViewById(R.id.buttonNewReview);
writeReview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG, "writeReview.onClick() >>");
Intent intent = new Intent(getApplicationContext(),ReviewActivity.class);
intent.putExtra("standup", standup);
intent.putExtra("key", key);
intent.putExtra("user",user);
startActivity(intent);
finish();
Log.e(TAG, "writeReview.onClick() <<");
}
});
recyclerViewStandupReviews = findViewById(R.id.standup_reviews);
recyclerViewStandupReviews.setHasFixedSize(true);
recyclerViewStandupReviews.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerViewStandupReviews.setItemAnimator(new DefaultItemAnimator());
ReviewsAdapter reviewsAdapter = new ReviewsAdapter(reviewsList);
recyclerViewStandupReviews.setAdapter(reviewsAdapter);
standupReviewsRef = FirebaseDatabase.getInstance().getReference("Standup/" + key +"/reviews");
standupReviewsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange() >> Standup/" + key);
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Review review = dataSnapshot.getValue(Review.class);
reviewsList.add(review);
}
recyclerViewStandupReviews.getAdapter().notifyDataSetChanged();
Log.e(TAG, "onDataChange(Review) <<");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Review) >>" + databaseError.getMessage());
}
});
Log.e(TAG, "onCreate() <<");
}
#Override
protected void onPause() {
super.onPause();
stopPlayingCurrentStandup();
}
private void playCurrentStandup(String standupFile) {
Log.e(TAG, "playCurrentStandup() >> standupFile=" + standupFile);
if (stopPlayingCurrentStandup()) {
Log.e(TAG, "playCurrentStandup() << Stop playing current Standup");
return;
}
FirebaseStorage.getInstance()
.getReference("StandupsFile/" + standupFile)
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUrl) {
Log.e(TAG, "onSuccess() >> " + downloadUrl.toString());
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl.toString()));
intent.setDataAndType(Uri.parse(downloadUrl.toString()), "video/mp4");
startActivity(intent);
//mediaPlayer.setDataSource(downloadUrl.toString());
//mediaPlayer.prepare(); // might take long! (for buffering, etc)
//mediaPlayer.start();
} catch (Exception e) {
Log.w(TAG, "playStandup() error:" + e.getMessage());
}
Log.e(TAG, "onSuccess() <<");
}
});
Log.e(TAG, "playCurrentStandup() << ");
}
private boolean stopPlayingCurrentStandup() {
if (mediaPlayer.isPlaying()) {
Log.e(TAG, "onSuccess() >> Stop the media player");
//Stop the media player
mediaPlayer.stop();
mediaPlayer.reset();
buyPlay.setText("PLAY");
return true;
}
return false;
}
}
ReviewActivity
public class ReviewActivity extends AppCompatActivity {
private final String TAG = "ReviewActivity";
private Standup standup;
private String key;
private User user;
private int prevRating = -1;
private TextView userReview;
private RatingBar userRating;
private DatabaseReference standupRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.e(TAG, "onCreate() >>");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review);
key = getIntent().getStringExtra("key");
standup = getIntent().getParcelableExtra("standup");
user = getIntent().getParcelableExtra("user");
userReview = findViewById(R.id.new_user_review);
userRating = findViewById(R.id.new_user_rating);
standupRef = FirebaseDatabase.getInstance().getReference("Standup/" + key);
standupRef.child("/reviews/" + FirebaseAuth.getInstance().getCurrentUser().getUid()).
addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange(Review) >> " + snapshot.getKey());
Review review = snapshot.getValue(Review.class);
if (review != null) {
userReview.setText(review.getUserReview());
userRating.setRating(review.getUserRating());
prevRating = review.getUserRating();
}
Log.e(TAG, "onDataChange(Review) <<");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Review) >>" + databaseError.getMessage());
}
});
Log.e(TAG, "onCreate() <<");
}
public void onSubmitClick(View v) {
Log.e(TAG, "onSubmitClick() >>");
standupRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Log.e(TAG, "doTransaction() >>" );
Standup standup = mutableData.getValue(Standup.class);
if (standup == null ) {
Log.e(TAG, "doTransaction() << standup is null" );
return Transaction.success(mutableData);
}
if (prevRating == -1) {
// Increment the review count and rating only in case the user enters a new review
standup.incrementReviewCount();
standup.incrementRating((int)userRating.getRating());
} else{
standup.incrementRating((int)userRating.getRating() - prevRating);
}
mutableData.setValue(standup);
Log.e(TAG, "doTransaction() << standup was set");
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) {
Log.e(TAG, "onComplete() >>" );
if (databaseError != null) {
Log.e(TAG, "onComplete() << Error:" + databaseError.getMessage());
return;
}
if (committed) {
Review review = new Review(
userReview.getText().toString(),
(int)userRating.getRating(),
user.getEmail());
standupRef.child("/reviews/" + FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(review);
}
Intent intent = new Intent(getApplicationContext(),StandupDetails.class);
intent.putExtra("standup", standup);
intent.putExtra("key", key);
intent.putExtra("user",user);
startActivity(intent);
finish();
Log.e(TAG, "onComplete() <<" );
}
});
Log.e(TAG, "onSubmitClick() <<");
}
}
StandupPlayerMain.java
public class StandupPlayerMain extends Activity {
private final String TAG = "StandUp Player Tag";
private DatabaseReference allStandupRef;
private DatabaseReference myUserRef;
private List<StandupWithKey> standupList = new ArrayList<>();
private GoogleSignInClient mGoogleSignInClient;
private RecyclerView recyclerView;
private VideoAdapter standupAdapter;
private User myUser;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_standup_player_main);
Log.e(TAG, "onCreate() >>");
mAuth= FirebaseAuth.getInstance();
recyclerView = (RecyclerView) findViewById(R.id.standups_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
if (fbUser != null) {
myUserRef = FirebaseDatabase.getInstance().getReference("Users/" + fbUser.getUid());
myUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange(User) >> " + snapshot.getKey());
myUser = snapshot.getValue(User.class);
getAllStandups();
Log.e(TAG, "onDataChange(User) <<");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Users) >>" + databaseError.getMessage());
}
});
Log.e(TAG, "onCreate() <<");
} else {
getAllStandups();
}
}
private void getAllStandups() {
Log.e(TAG,"GET ALL STANDUPS >>");
standupList.clear();
standupAdapter = new VideoAdapter(standupList,myUser);
recyclerView.setAdapter(standupAdapter);
//getAllSongsUsingValueListenrs();
getAllVideoUsingChildListenrs();
Log.e(TAG,"GET ALL STANDUPS <<");
}
private void getAllVideoUsingChildListenrs() {
allStandupRef = FirebaseDatabase.getInstance().getReference("Standup");
allStandupRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange(Standup) >> " + snapshot.getKey());
updateStandupList(snapshot);
Log.e(TAG, "onDataChange(Standup) <<");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Songs) >>" + databaseError.getMessage());
}
});
}
private void getAllSongsUsingChildListenrs() {
allStandupRef = FirebaseDatabase.getInstance().getReference("Standup");
allStandupRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName){
Log.e(TAG, "onChildAdded(Standup) >> " + snapshot.getKey());
StandupWithKey standupwithKey = new StandupWithKey(snapshot.getKey(),snapshot.getValue(Standup.class));
standupList.add(standupwithKey);
recyclerView.getAdapter().notifyDataSetChanged();
Log.e(TAG, "onChildAdded(Standup) <<");
}
#Override
public void onChildChanged(DataSnapshot snapshot, String previousChildName){
Log.e(TAG, "onChildChanged(Standup) >> " + snapshot.getKey());
Standup standup = snapshot.getValue(Standup.class);
String key = snapshot.getKey();
for (int i = 0 ; i < standupList.size() ; i++) {
StandupWithKey standupWithKey = (StandupWithKey) standupList.get(i);
if (standupWithKey.getKey().equals(snapshot.getKey())) {
standupWithKey.setStandup(standup);
recyclerView.getAdapter().notifyDataSetChanged();
break;
}
}
Log.e(TAG, "onChildChanged(Standup) <<");
}
#Override
public void onChildMoved(DataSnapshot snapshot, String previousChildName){
Log.e(TAG, "onChildMoved(Standup) >> " + snapshot.getKey());
Log.e(TAG, "onChildMoved(Standup) << Doing nothing");
}
#Override
public void onChildRemoved(DataSnapshot snapshot){
Log.e(TAG, "onChildRemoved(Standup) >> " + snapshot.getKey());
Standup standup =snapshot.getValue(Standup.class);
String key = snapshot.getKey();
for (int i = 0 ; i < standupList.size() ; i++) {
StandupWithKey standupwithKey = (StandupWithKey) standupList.get(i);
if (standupwithKey.getKey().equals(snapshot.getKey())) {
standupList.remove(i);
recyclerView.getAdapter().notifyDataSetChanged();
Log.e(TAG, "onChildRemoved(Standup) >> i="+i);
break;
}
}
Log.e(TAG, "onChildRemoved(Standup) <<");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled(Standup) >>" + databaseError.getMessage());
}
});
}
private void updateStandupList(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Standup standup = dataSnapshot.getValue(Standup.class);
Log.e(TAG, "updateStandupList() >> adding standup: " + standup.getName());
String key = dataSnapshot.getKey();
standupList.add(new StandupWithKey(key,standup));
}
recyclerView.getAdapter().notifyDataSetChanged();
}
public void onSignOutClick(View V) {
Log.e(TAG, "onSignOutClick() >>");
logOutFromGoogleAccount();
LoginManager.getInstance().logOut();
mAuth.signOut();
Intent intent = new Intent(StandupPlayerMain.this,LogInActivity.class);
startActivity(intent);
Log.e(TAG, "onSignOutClick() <<");
}
private void logOutFromGoogleAccount()
{
Log.e(TAG, "logOutFromGoogleAccount() >>");
GoogleSignInOptions gso = new GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestProfile()
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleSignInClient.signOut();
Log.e(TAG, "logOutFromGoogleAccount() <<");
}
public void onSearchButtonClick(View v) {
String searchString = ((EditText)findViewById(R.id.edit_text_search_standup)).getText().toString();
String orderBy = ((RadioButton)findViewById(R.id.radioButtonByReviews)).isChecked() ? "reviewsCount" : "price";
Query searchStandup;
Log.e(TAG, "onSearchButtonClick() >> searchString="+searchString+ ",orderBy="+orderBy);
standupList.clear();
if (searchString != null && !searchString.isEmpty()) {
searchStandup = allStandupRef.orderByChild("name").startAt(searchString).endAt(searchString + "\uf8ff");
} else {
searchStandup = allStandupRef.orderByChild(orderBy);
}
searchStandup.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.e(TAG, "onDataChange(Query) >> " + snapshot.getKey());
updateStandupList(snapshot);
Log.e(TAG, "onDataChange(Query) <<");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled() >>" + databaseError.getMessage());
}
});
Log.e(TAG, "onSearchButtonClick() <<");
}
public void onRadioButtonCLick(View v) {
switch (v.getId()) {
case R.id.radioButtonByPrice:
((RadioButton)findViewById(R.id.radioButtonByReviews)).setChecked(false);
break;
case R.id.radioButtonByReviews:
((RadioButton)findViewById(R.id.radioButtonByPrice)).setChecked(false);
break;
}
}
}
You're using the same layout for the StandupDetails activity and the recycler list item:
activity_standup_details.xml
setContentView(R.layout.activity_standup_details);
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_standup_details, parent, false);
You probably want to use different layouts. Because of that your findViewById in the view holder are returning null and that's why you're getting an NPE.
If you're using Butterknife inside your RecyclerAdapter this is the correct way to bind the ViewHolder
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
If you don't use this it will throw the error.