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.
Related
I set the like button in the recycler view but when I click on the like button in a different position so it comes back to the top of the class how can I make it the same situation when I click other place in the recycler view
here is the image
https://i.stack.imgur.com/Nh0PQ.jpg
public class SocialFragment extends Fragment
Toolbar toolbar;
RecyclerView post_rv;
List<PostModel> list;
PostAdapter adapter;
public SocialFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle saved instance state) {
// Inflate the layout for this fragment
View view inflater.inflate(R.layout.fragment_social, container, false);
toolbar = view.findViewById(R.id.social_header);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
ActionBar actionBar = activity.getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(true);
post_rv = view.findViewById(R.id.post_rv);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
post_rv.setLayoutManager(linearLayoutManager);
list = new ArrayList<>();
loadPost();
return view;
}
private void loadPost() {
DatabaseReference database reference = FirebaseDatabase.getInstance().getReference("Posts");
database reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot ds: snapshot.getChildren())
{
PostModel postModel = ds.getValue(PostModel.class);
list.add(postModel);
adapter = new PostAdapter(getActivity(),list);
post_rv.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void searchPost(String searchQuary){
DatabaseReference database reference = FirebaseDatabase.getInstance().getReference("Posts");
database reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot ds: snapshot.getChildren())
{
PostModel postModel = ds.getValue(PostModel.class);
if (postModel.getuName().toLowerCase().contains(searchQuary.toLowerCase()) || postModel.getpDesc().toLowerCase().contains(searchQuary.toLowerCase()))
{
list.add(postModel);
}
adapter = new PostAdapter(getActivity(),list);
post_rv.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.search_menu,menu);
MenuItem item = menu.findItem(R.id.search_users);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (!TextUtils.isEmpty(query))
{
searchPost(query);
}else {
loadPost();
}
return false;
}
#Override
public boolean onQueryTextChange(String query) {
if (!TextUtils.isEmpty(query))
{
searchPost(query);
}else {
loadPost();
}
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id==R.id.post_add){
Intent intent = new Intent(getActivity(),AddPostActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Adapter
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
List<PostModel> postList;
String myUid;
private DatabaseReference likeRef;
private DatabaseReference postRef;
boolean mProcessLikes = false;
public PostAdapter(Context context, List<PostModel> postList) {
this.context = context;
this.postList = postList;
myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
likeRef = FirebaseDatabase.getInstance().getReference().child("Likes");
postRef = FirebaseDatabase.getInstance().getReference().child("Posts");
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.social_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final String uid = postList.get(position).getUid();
String uName = postList.get(position).getuName();
String uEmail = postList.get(position).getuEmail();
String dp = postList.get(position).getDp();
final String pId = postList.get(position).getpId();
String pDesc = postList.get(position).getpDesc();
final String pImage = postList.get(position).getpImage();
String pTime = postList.get(position).getpTime();
String pLike = postList.get(position).getpLikes();
String pComments = postList.get(position).getpComments();
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(Long.parseLong(pTime));
String dateTime = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString();
holder.user_post_name.setText(uName);
holder.user_post_desc.setText(pDesc);
holder.user_post_time.setText(dateTime);
holder.count_likes.setText(pLike + "Likes");
holder.count_comments.setText(pComments + "Comments");
holder.user_post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, FullScreenImage.class);
intent.putExtra("url",postList.get(position).getpImage());
context.startActivity(intent);
}
});
setLikes(holder, pId);
try {
Picasso.get().load(dp).placeholder(R.drawable.profile).into(holder.user_post_dp);
} catch (Exception e) {
Picasso.get().load(R.drawable.profile).placeholder(R.drawable.profile).into(holder.user_post_dp);
e.printStackTrace();
}
if (pImage.equals("noImage")) {
holder.user_post_image.setVisibility(View.GONE);
} else {
holder.user_post_image.setVisibility(View.VISIBLE);
try {
Picasso.get().load(pImage).into(holder.user_post_image);
} catch (Exception e) {
e.printStackTrace();
}
}
holder.likeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pLike = Integer.parseInt(postList.get(position).getpLikes());
mProcessLikes = true;
String postIde = postList.get(position).getpId();
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (mProcessLikes) {
if (snapshot.child(postIde).hasChild(myUid)) {
posted.child(postIde).child("likes").setValue("" + (like - 1));
like.child(postIde).child(myUid).removeValue();
mProcessLikes = false;
} else {
postRef.child(postIde).child("pLikes").setValue("" + (pLike + 1));
likeRef.child(postIde).child(myUid).setValue("Liked");
mProcessLikes = false;
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
holder.commentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, PostDetailActivity.class);
intent.putExtra("postId", pId);
context.startActivity(intent);
}
});
holder.shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) holder.user_post_image.getDrawable();
if (bitmapDrawable==null)
{ //share without image
sharedTextOnly(press);
}else {
// share with image
Bitmap bitmap = bitmapDrawable.getBitmap();
shareImageAndText(pDesc,bitmap);
}
}
});
holder.profileLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra("uid", uid);
context.startActivity(intent);
}
});
holder.morebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showMoreButtonOption(holder.morebtn, uid, myUid, pId, pImage);
}
});
}
private void sharedTextOnly(String pDesc) {
String shareBody = pDesc;
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT,"Subject here");
intent.putExtra(Intent.EXTRA_TEXT,shareBody);
context.startActivity(Intent.createChooser(intent,"Share Via"));
}
private void shareImageAndText(String pDesc, Bitmap bitmap) {
String shareBody = pDesc;
Uri uri = savedImageToShare(bitmap);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,uri);
intent.putExtra(Intent.EXTRA_TEXT,shareBody);
intent.putExtra(Intent.EXTRA_SUBJECT,"Subject here");
intent.setType("image/png");
context.startActivity(Intent.createChooser(intent,"Share Via"));
}
private Uri savedImageToShare(Bitmap bitmap) {
File imageFolder = new File(context.getCacheDir(),"images");
Uri uri = null;
try {
imageFolder.mkdirs();
File file = new File(imageFolder,"share_image.png");
FileOutputStream stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,90,stream);
stream.flush();
stream.close();
uri = FileProvider.getUriForFile(context,"com.example.fire_safety.fileprovider",file);
} catch (Exception e) {
Toast.makeText(context, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return URI;
}
private void setLikes(final ViewHolder myHolder, final String postKey) {
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(postKey).hasChild(myUid)) {
myHolder.likeBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_iocn, 0, 0, 0);
myHolder.likeBtn.setText("Liked");
} else {
myHolder.likeBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_black, 0, 0, 0);
myHolder.likeBtn.setText("Like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void showMoreButtonOption(ImageButton morebtn, String uid, String myUid, String pId, String pImage) {
PopupMenu popupMenu = new PopupMenu(context, morebtn, Gravity.END);
if (uid.equals(myUid)) {
popupMenu.getMenu().add(Menu.NONE, 0, 0, "Delete");
// popupMenu.getMenu().add(Menu.NONE, 1, 0, "Edit");
}
popupMenu.getMenu().add(Menu.NONE, 1, 0, "View Details");
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == 0) {
beginDelete(pId, pImage);
} else if (id == 1) {
Intent intent = new Intent(context, PostDetailActivity.class);
intent.putExtra("postId", pId);
context.startActivity(intent);
}
return false;
}
});
popupMenu.show();
}
private void beginDelete(String pId, String pImage) {
if (pImage.equals("noImage")) {
deleteWithoutImage(pId);
} else {
deleteWithImage(pId, pImage);
}
}
private void deleteWithImage(String pId, String pImage) {
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Deleting...");
StorageReference picRef = FirebaseStorage.getInstance().getReferenceFromUrl(pImage);
picRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("pId").equalTo(pId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
ds.getRef().removeValue(); // remove value from database where pid matches
}
Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void deleteWithoutImage(String pId) {
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Deleting...");
Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("pId").equalTo(pId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
ds.getRef().removeValue(); // remove value from database where pid matches
}
Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return postList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView user_post_dp;
ImageView user_post_image;
TextView user_post_name, user_post_time, user_post_desc, count_likes,count_comments;
Button likeBtn, commentBtn, shareBtn;
ImageButton more in;
LinearLayout profile layout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
user_post_dp = itemView.findViewById(R.id.user_post_dp);
user_post_image = itemView.findViewById(R.id.user_post_image);
user_post_name = itemView.findViewById(R.id.user_post_name);
user_post_time = itemView.findViewById(R.id.user_post_time);
user_post_desc = itemView.findViewById(R.id.user_post_desc);
count_likes = itemView.findViewById(R.id.count_likes);
count_comments = itemView.findViewById(R.id.count_comments);
likeBtn = itemView.findViewById(R.id.likeBtn);
commentBtn = itemView.findViewById(R.id.commentBtn);
shareBtn = itemView.findViewById(R.id.shareBtn);
profileLayout = itemView.findViewById(R.id.profileLayout);
morebtn = itemView.findViewById(R.id.morebtn);
}
}
I initialy had Radio player i.e RadioActivity, which was working perfectly
The problem
I later decided to have a dashboad as the main activity where you can click a button to take you to the RadioActivty. Now app keeps crashing after splashscreen
Find The Codes Below
SplashScreen
private static int SPLASH_TIMER = 8000;
ImageView backgroundImage;
ImageView theLogo;
TextView poweredByLine;
Animation sideAnim, bottomAnim;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
getWindow().setFlags(WindowManager.LayoutParams.FLAGS_CHANGED,WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
setContentView(R.layout.activity_splash_screen);
backgroundImage = findViewById(R.id.background_image);
theLogo = findViewById(R.id.the_Logo);
poweredByLine = findViewById(R.id.powered_by_line);
sideAnim = AnimationUtils.loadAnimation(this, R.anim.side_anim);
bottomAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_anim);
backgroundImage.setAnimation(sideAnim);
theLogo.setAnimation(sideAnim);
poweredByLine.setAnimation(bottomAnim);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), OnBoarding.class);
startActivity(intent);
finish();
}
},SPLASH_TIMER);
}
}
OnBoarding
CardView nextCard;
LinearLayout dotsLayout;
ViewPager viewPager;
TextView[] dots;
int currentPosition;
SaveState saveState ;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);
nextCard = findViewById(R.id.nextCard);
dotsLayout = findViewById(R.id.dotsLayout);
viewPager = findViewById(R.id.slider);
dotsFunction(0);
saveState = new SaveState(OnBoarding.this,"OB");
if (saveState.getState() == 1){
Intent i = new Intent(OnBoarding.this,DashboardActivity.class);
startActivity(i);
finish();
}
OnBoardingAdapter adapter = new OnBoardingAdapter(this);
viewPager.setAdapter(adapter);
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1,true);
}
});
viewPager.setOnPageChangeListener(onPageChangeListener);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void dotsFunction(int pos){
dots = new TextView[4];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length ; i++){
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextColor(getColor(R.color.white)); //this is the non selection color
dots[i].setTextSize(30);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0){
dots[pos].setTextColor(getColor(R.color.teal_700)); //this is the selection color
dots[pos].setTextSize(40); //this is the selection size
}
}
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onPageSelected(int position) {
dotsFunction(position);
currentPosition = position;
if (currentPosition <= 2){
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1);
}
});
}else{
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveState.setState(1);
Intent i = new Intent(OnBoarding.this, DashboardActivity.class);
startActivity(i);
finish();
}
});
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
DashBoardActivity
public class DashboardActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView imageViewWebsite,imageViewEvents,imageViewLive,
imageViewVideos,imageViewBranches,imageViewDonate,
imageViewEkuwe,imageViewRadio,imageViewAudio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//defininf Cards
imageViewWebsite = (ImageView) findViewById(R.id.website_card);
imageViewEvents = (ImageView) findViewById(R.id.event_card);
imageViewLive = (ImageView) findViewById(R.id.live_card);
imageViewVideos = (ImageView) findViewById(R.id.videos_card);
imageViewBranches = (ImageView) findViewById(R.id.branches_card);
imageViewDonate = (ImageView) findViewById(R.id.donate_card);
imageViewEkuwe = (ImageView) findViewById(R.id.ekuwe_card);
imageViewRadio = (ImageView) findViewById(R.id.radio_card);
imageViewAudio = (ImageView) findViewById(R.id.audio_card);
//Add CLick listener to the card
imageViewWebsite.setOnClickListener(this);
imageViewEvents.setOnClickListener(this);
imageViewLive.setOnClickListener(this);
imageViewVideos.setOnClickListener(this);
imageViewBranches.setOnClickListener(this);
imageViewDonate.setOnClickListener(this);
imageViewEkuwe.setOnClickListener(this);
imageViewRadio.setOnClickListener(this);
imageViewAudio.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.website_card : i = new Intent(this, WebsiteActivity.class);startActivity(i); break;
case R.id.event_card : i = new Intent(this,EventsActivity.class);startActivity(i); break;
case R.id.live_card : i = new Intent(this, LiveActivity.class);startActivity(i); break;
case R.id.videos_card : i = new Intent(this, VideoActivity.class);startActivity(i); break;
case R.id.branches_card : i = new Intent(this,BranchesActivity.class);startActivity(i); break;
case R.id.donate_card : i = new Intent(this, DonateActivity.class);startActivity(i); break;
case R.id.ekuwe_card : i = new Intent(this,EkuweActivity.class);startActivity(i); break;
case R.id.radio_card : i = new Intent(this,RadioActivity.class);startActivity(i); break;
case R.id.audio_card : i = new Intent(this,AudioActivity.class);startActivity(i); break;
default:break;
}
}
}
RadioActivity
public class RadioActivity extends AppCompatActivity {
private TextView nowPlaying;
private ImageView playStop;
private BroadcastReceiver broadcastReceiver;
private String nowPlayingData = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
playStop = findViewById(R.id.playStopBtn);
nowPlaying = findViewById(R.id.radioStationNowPlaying);
setIsPlaying(false);
processPhoneListenerPermission();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
if (tm != null) {
if (tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
if (getIsPlaying()) {
stop();
}
System.exit(0);
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
registerReceiver(broadcastReceiver, filter);
loadNowPlaying();
playStop.setOnClickListener(view -> {
if (isNetworkAvailable()) {
if (getIsPlaying()) {
stop();
} else {
play();
}
} else {
Toast.makeText(getApplicationContext(), "No internet", Toast.LENGTH_LONG).show();
}
});
}
private void loadNowPlaying() {
Thread t = new Thread() {
public void run() {
try {
while (!isInterrupted()) {
runOnUiThread(() -> reloadShoutCastInfo());
Thread.sleep(20000);
}
} catch (InterruptedException ignored) {
}
}
};
t.start();
}
private void reloadShoutCastInfo() {
if (isNetworkAvailable()) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
}
#SuppressLint("StaticFieldLeak")
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource(STREAMING_URL);
nowPlayingData = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ICY_METADATA).replaceAll("StreamTitle", "").replaceAll("[=,';]+", "");
mmr.release();
return null;
}
#Override
protected void onPostExecute(String result) {
nowPlaying.setText(nowPlayingData);
}
}
private void processPhoneListenerPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 121);
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (cm != null) {
networkInfo = cm.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 121) {
if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(getApplicationContext(), "Permission not granted.\nWe can't pause music when phone ringing.", Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", (dialog, id) -> {
if (getIsPlaying()) {
stop();
}
System.exit(0);
})
.setNegativeButton("No", (dialog, id) -> dialog.cancel());
AlertDialog alert = builder.create();
alert.show();
}
private void setIsPlaying(boolean status) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE).edit();
editor.putBoolean("isPlaying", status);
editor.apply();
}
private boolean getIsPlaying() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE);
return prefs.getBoolean("isPlaying", false);
}
private void play() {
setIsPlaying(true);
Intent servicePlayIntent = new Intent(this, MyService.class);
servicePlayIntent.putExtra("playStop", "play");
startService(servicePlayIntent);
playStop.setImageResource(R.drawable.ic_pause);
Toast.makeText(getApplicationContext(), "Loading ...", Toast.LENGTH_LONG).show();
}
private void stop() {
setIsPlaying(false);
Intent serviceStopIntent = new Intent(this, MyService.class);
serviceStopIntent.putExtra("playStop", "stop");
startService(serviceStopIntent);
playStop.setImageResource(R.drawable.ic_play);
Toast.makeText(getApplicationContext(), "Stop Radio...", Toast.LENGTH_LONG).show();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
stopService(new Intent(getApplicationContext(), MyService.class));
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
}
OnBoardingAdapter
public class OnBoardingAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
public OnBoardingAdapter(Context context) {
this.context = context;
}
int titles[] = {
R.string.title1,
R.string.title2,
R.string.title3,
R.string.title4
};
int subtitles[] = {
R.string.subtitle1,
R.string.subtitle2,
R.string.subtitle3,
R.string.subtitle4
};
int images[] = {
R.drawable.on_boarding_vector_1,
R.drawable.on_boarding_vector_2,
R.drawable.on_boarding_vector_3,
R.drawable.on_boarding_vector_4
};
int bg[] = {
R.drawable.bg1,
R.drawable.bg2,
R.drawable.bg3,
R.drawable.bg4
};
#Override
public int getCount() {
return titles.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.slide,container,false);
ImageView image = v.findViewById(R.id.slideImg);
TextView title = v.findViewById(R.id.sliderTitle);
TextView subtitle = v.findViewById(R.id.sliderSubtitle);
ConstraintLayout layout = v.findViewById(R.id.sliderLayout);
image.setImageResource(images[position]);
title.setText(titles[position]);
subtitle.setText(subtitles[position]);
layout.setBackgroundResource(bg[position]);
container.addView(v);
return v;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
I found the solution to this, I had to turn to Design Mode and Inspected everything i
found the problem on line 18 DashboardActivity.xml
I changed this
com.google.android.material.bottomappbar.BottomAppBar to
com.google.android.material.appbar.AppBarLayout
I tried to make a different condition based on firebase database data. for example if the "Status" field data has value "Aktif" then the marker color will change to blue and when the "Status" value change into "Nonaktif" then the marker color will change into red. I already to use this code, but when tried to run it have the problem "error: incompatible types: cannot be converted to Context".
So how can i fix this problem? i will put the database structure here Firebase structure
private NavigationView navigationView;
private TextView namapengguna, emailpengguna;
private ImageView imageView2;
private View headerView;
DrawerLayout drawerLayout;
MapView mapView;
public MapboxMap mapboxMap;
private LocationManager manager;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
Marker myMarker;
private final int MIN_TIME = 1000;
private final int MIN_DISTANCE = 1;
private FirebaseUser user;
private DatabaseReference root;
private StorageReference reference;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoiaGFuZGlrYW1lZGlhbWFydGEiLCJhIjoiY2ttb2o1MWQ2MHp5cDJ3bHcyM3RkN2VvdiJ9.VOmbzomxo3nMMWLcmF2l0g");
setContentView(R.layout.activity_dashboard);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
mapView = (MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
namapengguna = (TextView) headerView.findViewById(R.id.namalengkap);
emailpengguna = (TextView) headerView.findViewById(R.id.emailpengguna);
imageView2 = findViewById(R.id.imageview2);
imageView2 = (ImageView) headerView.findViewById(R.id.imageview2);
user = FirebaseAuth.getInstance().getCurrentUser();
root = FirebaseDatabase.getInstance().getReference();
reference = FirebaseStorage.getInstance().getReference();
userID = user.getUid();
root.child("Users").child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userProfile = snapshot.getValue(User.class);
if (userProfile != null) {
String fullName = userProfile.fullname;
String email = userProfile.email;
namapengguna.setText(fullName);
emailpengguna.setText(email);
if (snapshot.hasChild("image")){
String image2 =snapshot.child("image").getValue().toString();
Picasso.get().load(image2).into(imageView2);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Dashboard.this, "Terjadi Kesalahan Pada Database", Toast.LENGTH_LONG).show();
}
});
}
public void ClickMenu(View view) {
openDrawer(drawerLayout);
}
public static void openDrawer(DrawerLayout drawerLayout) {
drawerLayout.openDrawer(GravityCompat.START);
}
public void ClickLogo(View view) {
closeDrawer(drawerLayout);
}
public static void closeDrawer(DrawerLayout drawerLayout) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
}
public void ClickHome(View view) {
recreate();
}
public void ClickUtama(View view) {
redirectActivity(this, Utama.class);
}
public void ClickAboutUs(View view) {
redirectActivity(this, AboutUs.class);
}
public void ClickLogout(View view) {
logout(this);
}
public static void logout(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Logout");
builder.setMessage("Are you sure want to logout?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
activity.finishAffinity();
System.exit(0);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
public static void redirectActivity(Activity activity, Class aClass) {
Intent intent = new Intent(activity, aClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
root.child("otoped").addValueEventListener(new ValueEventListener() {
Query q = FirebaseDatabase.getInstance().getReference("otoped").orderByChild("Status").equalTo("0");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyLocation location = dataSnapshot.getValue(MyLocation.class);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng loc = new LatLng(latitude,longitude);
if (q != null){
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_markerbiru)));
myMarker.setPosition(loc);
}else{
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.markerblue)).position(loc).title("Otoped1"));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
Drawable drawable = ResourcesCompat.getDrawable(getResources(),R.drawable.ic_baseline_location_on_24,null);
Bitmap mBitmap = BitmapUtils.getBitmapFromDrawable(drawable);
}
});
}
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(Dashboard.this)){
LocationComponent locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(Dashboard.this, loadedMapStyle).build());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
return;
}
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager((PermissionsListener) this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
closeDrawer(drawerLayout);
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLocationChanged(#NonNull Location location) {
if (location != null){
saveLocation(location);
}else {
Toast.makeText(this, "No Location", Toast.LENGTH_SHORT).show();
}
}
private void saveLocation(Location location) {
root.child("otoped").setValue(location);
}
}
I Got problem when tried to edit this code
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
root.child("otoped").addValueEventListener(new ValueEventListener() {
Query q = FirebaseDatabase.getInstance().getReference("otoped").orderByChild("Status").equalTo("0");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyLocation location = dataSnapshot.getValue(MyLocation.class);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng loc = new LatLng(latitude,longitude);
if (q != null){
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_markerbiru)));
myMarker.setPosition(loc);
}else{
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.markerblue)).position(loc).title("Otoped1"));
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
enter image description here
I recently started learning Java and decided to create an application. When registering, it shows the username in my database, but not in the application itself.I thought I had a problem with id but, no, everything is correct there. I've been looking for the second day and I just can't figure out what the problem is. Thanks in advance for solving the problem. What is the problem?
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final int REQUEST_CODE = 101;
Toolbar toolbar;
DrawerLayout drawerLayout;
NavigationView navigationView;
FirebaseAuth mAuth;
FirebaseUser mUser;
DatabaseReference mUserRef, PostRef, LikeRef, commentRef;
String profileImageUrlV, usernameV;
CircleImageView profileImageHeader;
TextView username_header;
ImageView addImagePost, sendImagePost;
EditText inputPostDesc;
Uri imageUri;
ProgressDialog mLoadingBar;
StorageReference postImageRef;
FirebaseRecyclerAdapter<Posts, MyViewHolder> adapter;
FirebaseRecyclerOptions<Posts> options;
RecyclerView recyclerView;
FirebaseRecyclerOptions<Comment> CommentOption;
FirebaseRecyclerAdapter<Comment, CommentViewHolder> CommentAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
addImagePost = findViewById(R.id.addimagePost);
sendImagePost = findViewById(R.id.send_post_imageView);
inputPostDesc = findViewById(R.id.inputAddPost);
mLoadingBar = new ProgressDialog(this);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostRef = FirebaseDatabase.getInstance().getReference().child("Posts");
LikeRef = FirebaseDatabase.getInstance().getReference().child("Likes");
commentRef = FirebaseDatabase.getInstance().getReference().child("Comments");
postImageRef = FirebaseStorage.getInstance().getReference().child("PostImages");
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.navView);
View view = navigationView.inflateHeaderView(R.layout.drawer_header);
profileImageHeader = view.findViewById(R.id.profileImage_header);
username_header = view.findViewById(R.id.username_header);
navigationView.setNavigationItemSelectedListener(this);
sendImagePost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPost();
}
});
addImagePost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE);
}
});
LoadPost();
}
private void LoadPost()
{
options = new FirebaseRecyclerOptions.Builder<Posts>().setQuery(PostRef, Posts.class).build();
adapter = new FirebaseRecyclerAdapter<Posts, MyViewHolder>(options)
{
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull Posts model) {
final String postKey = getRef(position).getKey();
holder.postDesc.setText(model.getPostDesc());
String timeAgo = calculateTimeAgo(model.getDatePost());
holder.timeAgo.setText(timeAgo);
holder.username.setText(model.getUsername());
Picasso.get().load(model.getPostImageUrl()).into(holder.postImage);
Picasso.get().load(model.getUserProfileImageUrl()).into(holder.profileImage);
holder.countLikes(postKey, mUser.getUid(), LikeRef);
holder.countComments(postKey, mUser.getUid(), commentRef);
holder.likeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LikeRef.child(postKey).child(mUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
LikeRef.child(postKey).child(mUser.getUid()).removeValue();
holder.likeImage.setColorFilter(Color.GRAY);
} else {
LikeRef.child(postKey).child(mUser.getUid()).setValue("Like");
holder.likeImage.setColorFilter(Color.GREEN);
}
notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
holder.commentSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String comment = holder.inputComments.getText().toString();
if (comment.isEmpty()) {
Toast.makeText(MainActivity.this, "Please write something in EditText", Toast.LENGTH_SHORT).show();
} else {
AddComment(holder, postKey, commentRef, mUser.getUid(), comment);
}
}
});
LoadComment(postKey);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_post, parent, false);
return new MyViewHolder(view);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
private void LoadComment(String postKey) {
MyViewHolder.recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
CommentOption = new FirebaseRecyclerOptions.Builder<Comment>().setQuery(commentRef.child(postKey), Comment.class).build();
CommentAdapter = new FirebaseRecyclerAdapter<Comment, CommentViewHolder>(CommentOption) {
#Override
protected void onBindViewHolder(#NonNull CommentViewHolder holder, int position, #NonNull Comment model) {
Picasso.get().load(model.getProfileImageUrl()).into(holder.profileImage);
holder.username.setText(model.getUsername());
holder.comment.setText(model.getComment());
}
#NonNull
#Override
public CommentViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_comment, parent, false);
return new CommentViewHolder(view);
}
};
CommentAdapter.startListening();
MyViewHolder.recyclerView.setAdapter(CommentAdapter);
}
private void AddComment(MyViewHolder holder, String postKey, DatabaseReference commentRef, String uid, String comment) {
HashMap hashMap = new HashMap();
hashMap.put("username", usernameV);
hashMap.put("profileImageUrl", profileImageUrlV);
hashMap.put("comment", comment);
commentRef.child(postKey).child(uid).updateChildren(hashMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Comment Added", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
holder.inputComments.setText(null);
} else {
Toast.makeText(MainActivity.this, "" + task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
private String calculateTimeAgo(String datePost) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
try {
long time = sdf.parse(datePost).getTime();
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
return ago + "";
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
addImagePost.setImageURI(imageUri);
}
}
private void AddPost() {
String postDesc = inputPostDesc.getText().toString();
if (postDesc.isEmpty() || postDesc.length() < 1) {
inputPostDesc.setError("Please write something in post");
} else if (imageUri == null) {
Toast.makeText(this, "Please select an image", Toast.LENGTH_SHORT).show();
} else {
mLoadingBar.setTitle("Твой пост добавляется пожалуйста потерпи немного)");
mLoadingBar.setCanceledOnTouchOutside(false);
mLoadingBar.show();
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String strDate = formatter.format(date);
postImageRef.child(mUser.getUid() + strDate).putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
postImageRef.child(mUser.getUid() + strDate).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
HashMap hashMap = new HashMap();
hashMap.put("datePost", strDate);
hashMap.put("postImageUrl", uri.toString());
hashMap.put("postDesc", postDesc);
hashMap.put("userProfileImageUrl", profileImageUrlV);
hashMap.put("username", usernameV);
PostRef.child(mUser.getUid() + strDate).updateChildren(hashMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
mLoadingBar.dismiss();
Toast.makeText(MainActivity.this, "Пост добавлен)", Toast.LENGTH_SHORT).show();
addImagePost.setImageResource(R.drawable.ic_add_post_image);
inputPostDesc.setText("");
} else {
mLoadingBar.dismiss();
Toast.makeText(MainActivity.this, "" + task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
mLoadingBar.dismiss();
Toast.makeText(MainActivity.this, "" + task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onStart() {
super.onStart();
if (mUser == null) {
SendUserToLoginActivity();
} else {
mUserRef.child(mUser.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
profileImageUrlV = dataSnapshot.child("profileImage").getValue().toString();
usernameV = dataSnapshot.child("username").getValue().toString();
Picasso.get().load(profileImageUrlV).into(profileImageHeader);
username_header.setText(usernameV);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, "Sorry!, Something going wrong", Toast.LENGTH_SHORT).show();
}
});
}
}
private void SendUserToLoginActivity() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
break;
case R.id.profile:
startActivity(new Intent(MainActivity.this, ProfileActivity.class));
break;
case R.id.friend:
Toast.makeText(this, "Friend", Toast.LENGTH_SHORT).show();
break;
case R.id.find_friend:
startActivity(new Intent(MainActivity.this, FindFriendActivity.class));
break;
case R.id.chat:
Toast.makeText(this, "Chat", Toast.LENGTH_SHORT).show();
break;
case R.id.Logout:
Toast.makeText(this, "Logout", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return true;
}
}
Replace this
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users");
with
mUserRef = FirebaseDatabase.getInstance().getReference().child("User");
Child name should be same
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