remain same position like button in recyclerview android - java

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);
}
}

Related

I have a problem with displaying username. It outputs to the database, but not to the application itself [closed]

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

How can I pause exoplayer when i swipe ViewPager2?

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

error for retrieving an images from firebase

I am having this error while deleting an image from application
E/InputEventReceiver: Exception dispatching input event.
E/MessageQueue-JNI: Exception in MessageQueue callback:
handleReceiveCallback E/MessageQueue-JNI:
java.lang.IllegalArgumentException: The storage Uri could not be
parsed.
This i my code i write it for deletion
Images_Actvity.java:
public class Images_Avctivity extends AppCompatActivity implements Image_adapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private Image_adapter mAdapter;
private ProgressBar mProgressCircle;
private FirebaseStorage mStorage;
private DatabaseReference mDatabaseRef;
private ValueEventListener mDBListener;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images__avctivity);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.progress_circle);
mUploads = new ArrayList<>();
mAdapter = new Image_adapter(Images_Avctivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(Images_Avctivity.this);
mStorage = FirebaseStorage.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
upload.setKey(postSnapshot.getKey());
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Images_Avctivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "Normal click at position: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onWhatEverClick(int position) {
Toast.makeText(this, "Whatever click at position: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onDeleteClick(int position) {
Upload selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl());
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mDatabaseRef.child(selectedKey).removeValue();
Toast.makeText(Images_Avctivity.this, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mDatabaseRef.removeEventListener(mDBListener);
}
}
This is adpater code:
Image_adapter.java:
public class Image_adapter extends RecyclerView.Adapter<Image_adapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;
public Image_adapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.with(mContext)
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
doWhatever.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onWhatEverClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onWhatEverClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/***********************-5fac-45b6-bbda-ed4e8a3a62ab");
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Log.e("firebasestorage", "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.e("firebasestorage", "onFailure: did not delete file");
}
});

PostAdapter returning incorrect postids for posts

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

(unchecked) unchecked cast required: OnSuccessListener found: Uri

I am developing an android application on Android Studio With Firebase and i am having the following error:
[unchecked] unchecked cast
required: OnSuccessListener
found: Uri
When I click to Show where is the problem it takes me to this code:
private void uploadImageToFirebaseStorage() {
final StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/"+System.currentTimeMillis()+".jpg");
if(uriProfileImage!=null){
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileImageRef.getDownloadUrl().addOnSuccessListener((OnSuccessListener<? super Uri>) uriProfileImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
Down here is the whole class:
public class Profile extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
TextView textView;
EditText editText;
ImageView imageView;
String profileimageurl;
private StorageReference mStorageRef;
Uri uriProfileImage;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mStorageRef = FirebaseStorage.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editText =(EditText)findViewById(R.id.nome);
imageView=(ImageView) findViewById(R.id.prefil);
textView=(TextView) findViewById(R.id.textViewVerified);
imageView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
showImageChooser();
}
});
loadUserInformation();
findViewById(R.id.login_bt).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserInformation();
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser()!=null){
finish();
startActivity(new Intent(this,Login.class));
}
}
private void loadUserInformation() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getPhotoUrl() != null) {
String photoUrl = user.getPhotoUrl().toString();
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(imageView);
}
if (user.getDisplayName() != null) {
String displayName = user.getDisplayName();
editText.setText(user.getDisplayName());
}
if (user.isEmailVerified()) {
textView.setText("Email verified");
}
else{
textView.setText("Email not Verified(click to Verify");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(Profile.this,"Verification Email Sent",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
}
private void saveUserInformation() {
String displayName = editText.getText().toString();
if(displayName.isEmpty()){
editText.setError("Requer Nome");
editText.requestFocus();
return;
}
FirebaseUser user = mAuth.getCurrentUser();
if(user!=null && profileimageurl!=null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
.setDisplayName(displayName)
.setPhotoUri(Uri.parse(profileimageurl))
.build();
user.updateProfile(profile)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if( task.isSuccessful()){
Toast.makeText(Profile.this,"Profile Updated",Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CHOOSE_IMAGE&& data !=null && data.getData()!=null){
uriProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),uriProfileImage);
imageView.setImageBitmap(bitmap);
uploadImageToFirebaseStorage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImageToFirebaseStorage() {
final StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/"+System.currentTimeMillis()+".jpg");
if(uriProfileImage!=null){
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileImageRef.getDownloadUrl().addOnSuccessListener((OnSuccessListener<? super Uri>) uriProfileImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this,Login.class));
break;
}
return true;
}
private void showImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Escohe a imagem de perfil"),CHOOSE_IMAGE);
}
}

Categories

Resources