java.lang.ClassCastException: ViewHolderItem cannot be cast to AnotherViewHolderItem - java

I'm trying to filter posts types (for example only images, audio, videos.....) and change the adapter to update items inside recycler view. But for some reason the first time i make any changes to my filter dialog the feature works without problems, but if i try to make any changes for 2nd time inside my dialog, i'm getting an java.lang.ClassCastException.
Error:
java.lang.ClassCastException: com.george.socialmeme.ViewHolders.ImageItemViewHolder cannot be cast to com.george.socialmeme.ViewHolders.VideoItemViewHolder
Method that displays the filter dialog:
void showFiltersDialog() {
Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.posts_filter_bottom_sheet);
View imagesItem = dialog.findViewById(R.id.view23);
View videosItem = dialog.findViewById(R.id.view21);
View soundsItem = dialog.findViewById(R.id.view22);
View textItem = dialog.findViewById(R.id.view20);
Button applyFiltersBtn = dialog.findViewById(R.id.apply_filters);
if (!imagesItemSelected[0]) {
dialog.findViewById(R.id.imageView30).setVisibility(View.GONE);
}
if (!videosItemSelected[0]) {
dialog.findViewById(R.id.imageView32).setVisibility(View.GONE);
}
if (!soundsItemSelected[0]) {
dialog.findViewById(R.id.imageView34).setVisibility(View.GONE);
}
if (!textItemSelected[0]) {
dialog.findViewById(R.id.imageView36).setVisibility(View.GONE);
}
imagesItem.setOnClickListener(view -> {
if (imagesItemSelected[0]) {
imagesItemSelected[0] = false;
dialog.findViewById(R.id.imageView30).setVisibility(View.GONE);
} else {
imagesItemSelected[0] = true;
dialog.findViewById(R.id.imageView30).setVisibility(View.VISIBLE);
}
});
videosItem.setOnClickListener(view -> {
if (videosItemSelected[0]) {
videosItemSelected[0] = false;
dialog.findViewById(R.id.imageView32).setVisibility(View.GONE);
} else {
videosItemSelected[0] = true;
dialog.findViewById(R.id.imageView32).setVisibility(View.VISIBLE);
}
});
soundsItem.setOnClickListener(view -> {
if (soundsItemSelected[0]) {
soundsItemSelected[0] = false;
dialog.findViewById(R.id.imageView34).setVisibility(View.GONE);
} else {
soundsItemSelected[0] = true;
dialog.findViewById(R.id.imageView34).setVisibility(View.VISIBLE);
}
});
textItem.setOnClickListener(view -> {
if (textItemSelected[0]) {
textItemSelected[0] = false;
dialog.findViewById(R.id.imageView36).setVisibility(View.GONE);
} else {
textItemSelected[0] = true;
dialog.findViewById(R.id.imageView36).setVisibility(View.VISIBLE);
}
});
applyFiltersBtn.setOnClickListener(view -> {
filteredPostsArrayList.clear();
applyFiltersBtn.setText("Filtering...");
applyFiltersBtn.setEnabled(false);
dialog.setCancelable(false);
for (PostModel postModel : postModelArrayList) {
if (postModel.getPostType().equals("image")) {
if (imagesItemSelected[0]) {
filteredPostsArrayList.add(postModel);
}
}
if (postModel.getPostType().equals("video")) {
if (videosItemSelected[0]) {
filteredPostsArrayList.add(postModel);
}
}
if (postModel.getPostType().equals("audio")) {
if (soundsItemSelected[0]) {
filteredPostsArrayList.add(postModel);
}
}
if (postModel.getPostType().equals("text")) {
if (textItemSelected[0]) {
filteredPostsArrayList.add(postModel);
}
}
}
// Update RecyclerView adapter
recyclerAdapter = new PostRecyclerAdapter(filteredPostsArrayList, getContext(), getActivity());
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setStackFromEnd(true);
layoutManager.setReverseLayout(true);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setLayoutManager(layoutManager);
// Add post's of the month view as RecyclerView item
// to avoid using ScrollView
PostModel postsOfTheMonthView = new PostModel();
postsOfTheMonthView.setPostType("postsOfTheMonth");
filteredPostsArrayList.add(postsOfTheMonthView);
recyclerAdapter.notifyDataSetChanged();
dialog.dismiss();
});
dialog.show();
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(android.view.Gravity.BOTTOM);
}
My PostRecyclerAdapter class:
public class PostRecyclerAdapter extends RecyclerView.Adapter {
List<PostModel> postList;
Context context;
Activity activity;
#Override
public int getItemViewType(int position) {
if (postList.get(position).getPostType().equals("video")) {
return 1;
}
if (postList.get(position).getPostType().equals("postsOfTheMonth")) {
return 2;
}
if (postList.get(position).getPostType().equals("audio")) {
return 3;
}
if (postList.get(position).getPostType().equals("text")) {
return 4;
}
return 0;
}
public PostRecyclerAdapter(ArrayList<PostModel> postModelArrayList, Context context, Activity activity) {
this.postList = postModelArrayList;
this.context = context;
this.activity = activity;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == 1) {
return new VideoItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.video_post_item, parent, false));
}
if (viewType == 2) {
return new PostsOfTheMonthItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.posts_of_the_month_view_item, parent, false));
}
if (viewType == 3) {
return new AudioItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.audio_post_item, parent, false));
}
if (viewType == 4) {
return new PostTextItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.text_post_item, parent, false));
}
return new ImageItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.image_post_item, parent, false));
}
// Release ExoPlayer when a video item is recycled
// to avoid player errors on other video items inside RecyclerView
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if (postList.get(holder.getLayoutPosition()).getPostType().equals("video")) {
VideoItemViewHolder videoViewHolder = (VideoItemViewHolder) holder;
videoViewHolder.andExoPlayerView.getPlayer().release();
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
DatabaseReference likeRef = FirebaseDatabase.getInstance().getReference("likes");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
if (postList.get(position).getPostType().equals("postsOfTheMonth")) {
PostsOfTheMonthItemViewHolder viewHolder = (PostsOfTheMonthItemViewHolder) holder;
viewHolder.setContext(context);
}
if (postList.get(position).getPostType().equals("text")) {
// Bind audio view holder
PostTextItemViewHolder textItemViewHolder = (PostTextItemViewHolder) holder;
textItemViewHolder.setContext(context);
if (HomeActivity.singedInAnonymously) {
textItemViewHolder.commentsCount.setVisibility(View.GONE);
textItemViewHolder.postOptionsButton.setVisibility(View.GONE);
textItemViewHolder.openCommentsView.setVisibility(View.GONE);
textItemViewHolder.shareBtn.setVisibility(View.GONE);
}else {
if (user.getUid().equals(postList.get(position).getAuthorID())) {
textItemViewHolder.followBtnView.setVisibility(View.GONE);
}
}
// check if post is liked or not
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (!HomeActivity.singedInAnonymously) {
// check if current post is liked from this user
if (snapshot.child(textItemViewHolder.postID).hasChild(user.getUid())) {
// post is liked form this user
textItemViewHolder.like_btn.setImageResource(R.drawable.ic_like_filled);
textItemViewHolder.isPostLiked = true;
} else {
// post is not liked from this user
textItemViewHolder.like_btn.setImageResource(R.drawable.ic_like);
textItemViewHolder.isPostLiked = false;
}
} else {
textItemViewHolder.like_btn.setEnabled(false);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
textItemViewHolder.postID = postList.get(position).getId();
textItemViewHolder.username.setText(postList.get(position).getName());
textItemViewHolder.postAuthorID = postList.get(position).getAuthorID();
textItemViewHolder.like_counter_tv.setText(postList.get(position).getLikes());
textItemViewHolder.commentsCount.setText(postList.get(position).getCommentsCount());
// Load Title and content for the post
textItemViewHolder.postTitle.setText(postList.get(position).getPostTitle());
textItemViewHolder.postContentText.setText(postList.get(position).getPostContentText());
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(textItemViewHolder.profilePicture);
}
}
textItemViewHolder.shareBtn.setOnClickListener(view -> {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post_url", postList.get(position).getImgUrl());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Audio URL copied to clipboard", Toast.LENGTH_SHORT).show();
});
}
if (postList.get(position).getPostType().equals("audio")) {
// Bind audio view holder
AudioItemViewHolder audioViewHolder = (AudioItemViewHolder) holder;
audioViewHolder.setContext(context);
if (HomeActivity.singedInAnonymously) {
audioViewHolder.commentsCounter.setVisibility(View.GONE);
audioViewHolder.postOptionsBtn.setVisibility(View.GONE);
audioViewHolder.openCommentsView.setVisibility(View.GONE);
audioViewHolder.shareBtn.setVisibility(View.GONE);
}else {
if (user.getUid().equals(postList.get(position).getAuthorID())) {
audioViewHolder.followBtnView.setVisibility(View.GONE);
}
}
// check if post is liked or not
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (!HomeActivity.singedInAnonymously) {
// check if current post is liked from this user
if (snapshot.child(audioViewHolder.postID).hasChild(user.getUid())) {
// post is liked form this user
audioViewHolder.likeBtn.setImageResource(R.drawable.ic_like_filled);
audioViewHolder.isPostLiked = true;
} else {
// post is not liked from this user
audioViewHolder.likeBtn.setImageResource(R.drawable.ic_like);
audioViewHolder.isPostLiked = false;
}
} else {
// disable like button
audioViewHolder.likeBtn.setEnabled(false);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
audioViewHolder.postID = postList.get(position).getId();
audioViewHolder.usernameTV.setText(postList.get(position).getName());
audioViewHolder.postAuthorID = postList.get(position).getAuthorID();
audioViewHolder.likesCounter.setText(postList.get(position).getLikes());
audioViewHolder.audioURL = postList.get(position).getImgUrl();
audioViewHolder.audioName.setText(postList.get(position).getAudioName());
audioViewHolder.commentsCounter.setText(postList.get(position).getCommentsCount());
// Load audio source
audioViewHolder.audioPlayerView.withUrl(postList.get(position).getImgUrl());
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(audioViewHolder.profilePicture);
}
}
audioViewHolder.shareBtn.setOnClickListener(view -> {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post_url", postList.get(position).getImgUrl());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Audio URL copied to clipboard", Toast.LENGTH_SHORT).show();
});
}
if (postList.get(position).getPostType().equals("video")) {
// bind video view holder
VideoItemViewHolder videoViewHolder = (VideoItemViewHolder) holder;
videoViewHolder.setContext(context);
if (HomeActivity.singedInAnonymously) {
videoViewHolder.commentsCount.setVisibility(View.GONE);
videoViewHolder.postOptionsButton.setVisibility(View.GONE);
videoViewHolder.commentsBtn.setVisibility(View.GONE);
videoViewHolder.shareBtn.setVisibility(View.GONE);
}else {
if (user.getUid().equals(postList.get(position).getAuthorID())) {
videoViewHolder.followBtnView.setVisibility(View.GONE);
}
}
// check if post is liked or not
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (!HomeActivity.singedInAnonymously) {
// check if current post is liked from this user
if (snapshot.child(videoViewHolder.postID).hasChild(user.getUid())) {
// post is liked form this user
videoViewHolder.like_btn.setImageResource(R.drawable.ic_like_filled);
videoViewHolder.isPostLiked = true;
} else {
// post is not liked from this user
videoViewHolder.isPostLiked = false;
videoViewHolder.like_btn.setImageResource(R.drawable.ic_like);
}
} else {
// disable like button
videoViewHolder.like_btn.setEnabled(false);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "error: " + error, Toast.LENGTH_SHORT).show();
}
});
videoViewHolder.postID = postList.get(position).getId();
videoViewHolder.username.setText(postList.get(position).getName());
videoViewHolder.postAuthorID = postList.get(position).getAuthorID();
videoViewHolder.like_counter_tv.setText(postList.get(position).getLikes());
videoViewHolder.videoURL = postList.get(position).getImgUrl();
videoViewHolder.commentsCount.setText(postList.get(position).getCommentsCount());
// Load video source
ExoPlayer player = new ExoPlayer.Builder(context).build();
MediaItem mediaItem = MediaItem.fromUri(postList.get(position).getImgUrl());
player.setMediaItem(mediaItem);
player.prepare();
videoViewHolder.andExoPlayerView.setPlayer(player);
player.addAnalyticsListener(new AnalyticsListener() {
#Override
public void onPlayerError(#NonNull EventTime eventTime, #NonNull PlaybackException error) {
//Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
Log.i("EXOPLAYER_ERROR", "" + error.getMessage());
}
});
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(videoViewHolder.profilePicture);
}
}
videoViewHolder.shareBtn.setOnClickListener(view -> {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post_url", postList.get(position).getImgUrl());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Video URL copied to clipboard", Toast.LENGTH_SHORT).show();
});
}
if (postList.get(position).getPostType().equals("image")) {
// bind image view holder
ImageItemViewHolder imageViewHolder = (ImageItemViewHolder) holder;
imageViewHolder.setContext(context);
if (HomeActivity.singedInAnonymously) {
imageViewHolder.commentsCount.setVisibility(View.GONE);
imageViewHolder.show_comments_btn.setVisibility(View.GONE);
imageViewHolder.showPostOptionsButton.setVisibility(View.GONE);
imageViewHolder.shareBtn.setVisibility(View.GONE);
}else {
if (user.getUid().equals(postList.get(position).getAuthorID())) {
imageViewHolder.followBtnView.setVisibility(View.GONE);
}
}
// check if post is liked or not from the user
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (!HomeActivity.singedInAnonymously) {
// check if current post is liked from this user
if (snapshot.child(imageViewHolder.postID).hasChild(user.getUid())) {
// post is liked form this user
imageViewHolder.like_btn.setImageResource(R.drawable.ic_like_filled);
imageViewHolder.isPostLiked = true;
} else {
// post is not liked from this user
imageViewHolder.isPostLiked = false;
imageViewHolder.like_btn.setImageResource(R.drawable.ic_like);
}
} else {
imageViewHolder.like_btn.setEnabled(false);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "error: " + error, Toast.LENGTH_SHORT).show();
}
});
imageViewHolder.postID = postList.get(position).getId();
imageViewHolder.username.setText(postList.get(position).getName());
imageViewHolder.postAuthorID = postList.get(position).getAuthorID();
imageViewHolder.like_counter_tv.setText(postList.get(position).getLikes());
imageViewHolder.commentsCount.setText(postList.get(position).getCommentsCount());
Picasso.get().load(postList.get(position).getImgUrl()).into(imageViewHolder.postImg, new Callback() {
#Override
public void onSuccess() {
imageViewHolder.loadingProgressBar.setVisibility(View.GONE);
}
#Override
public void onError(Exception e) {
Toast.makeText(context, "Can't load this image: " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
imageViewHolder.postImageURL = postList.get(position).getImgUrl();
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(imageViewHolder.profileImage);
}
}
imageViewHolder.shareBtn.setOnClickListener(view -> {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post_url", postList.get(position).getImgUrl());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Image URL copied to clipboard", Toast.LENGTH_SHORT).show();
});
}
}
#Override
public int getItemCount() {
return postList.size();
}
}

It seems you're trying to cast item which is not an instance of VideoItemViewHolder to VideoItemViewHolder. Before making cast, check if the item is an instance of VideoItemViewHolder:
if(holder instanceof VideoItemViewHolder){
VideoItemViewHolder videoViewHolder = (VideoItemViewHolder) holder;
//Do your stuff...
} else {
//Cast cannot be done
}

Related

Am trying to register but keep getting errors in my android application please what is the solution

I am not too good at android applications so most of the code are from the Youtube videos I watched while trying to learn how to code android application. I made some adjustment to what I want.
Here I am stuck trying to create a library management system. Every thing seems to be
working, except for the fact that I can't create a new user or sign in.
Code is running fine, but still do not understand the errors. From my Sign Activity there seems to be a misplacement of code, which I don't understand.
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout editName;
private TextInputLayout editEnrollNo;
private TextInputLayout editCardNo;
private TextInputLayout editPass1;
private TextInputLayout editID;
private TextInputLayout editPass;
private Button buttonRegister;
private TextView toSignIn;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private CheckBox check1;
private FirebaseFirestore db;
private Spinner userType;
private String type;
private int type1;
private int temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
editID = (TextInputLayout) findViewById(R.id.editID);
editPass = (TextInputLayout) findViewById(R.id.editPass);
editPass1=(TextInputLayout)findViewById(R.id.editPass1);
editName=(TextInputLayout)findViewById(R.id.editName);
editEnrollNo=(TextInputLayout)findViewById(R.id.editEnrollNo);
editCardNo=(TextInputLayout)findViewById(R.id.editCardNo);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
toSignIn = (TextView) findViewById(R.id.toSignIn);
progressDialog=new ProgressDialog(this);
progressDialog.setCancelable(false);
check1=(CheckBox)findViewById(R.id.check1);
userType=(Spinner)findViewById(R.id.userType);
List<String> list = new ArrayList<>();
list.add("Select Account Type");
list.add("User");
list.add("Admin");
ArrayAdapter adapter =new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
userType.setAdapter(adapter);
userType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).toString().equals("Select Account Type"))
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(false);
editPass.setEnabled(false);
editName.setEnabled(false);
editID.setEnabled(false);
editEnrollNo.setEnabled(false);
editCardNo.setEnabled(false);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
else if(parent.getItemAtPosition(position).toString().equals("User"))
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(true);
editPass.setEnabled(true);
editName.setEnabled(true);
editID.setEnabled(true);
editEnrollNo.setEnabled(true);
editCardNo.setEnabled(true);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
else
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(true);
editPass.setEnabled(true);
editName.setEnabled(true);
editID.setEnabled(true);
editEnrollNo.setEnabled(false);
editCardNo.setEnabled(false);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
FirebaseApp.initializeApp(this);
firebaseAuth=FirebaseAuth.getInstance();
db=FirebaseFirestore.getInstance();
buttonRegister.setOnClickListener(this);
toSignIn.setOnClickListener(this);
check1.setOnClickListener(this);
}
private boolean verifyName()
{
String name=editName.getEditText().getText().toString().trim();
if(name.isEmpty())
{ editName.setErrorEnabled(true);
editName.setError("Name Required");
return true;
}
else
{
editName.setErrorEnabled(false);
return false;
}
}
private boolean verifyCardNo()
{
String cardNo=editCardNo.getEditText().getText().toString().trim();
if(cardNo.isEmpty())
{ editCardNo.setErrorEnabled(true);
editCardNo.setError("Card No. Required");
return true;
}
else
{
editCardNo.setErrorEnabled(false);
return false;
}
}
private boolean verifyEnrollNo()
{
String enrollNo=editEnrollNo.getEditText().getText().toString().trim();
if(enrollNo.isEmpty())
{ editEnrollNo.setErrorEnabled(true);
editEnrollNo.setError("Enrollment No. Required");
return true;
}
else
{
editEnrollNo.setErrorEnabled(false);
return false;
}
}
private boolean verifyEmailId()
{
String emailId=editID.getEditText().getText().toString().trim();
if(emailId.isEmpty())
{ editID.setErrorEnabled(true);
editID.setError(" Email ID Required");
return true;
}
else if(!emailId.endsWith("#iiitnr.edu.in"))
{
editID.setErrorEnabled(true);
editID.setError(" Enter Valid Email ID");
return true;
}
else
{
editID.setErrorEnabled(false);
return false;
}
}
private boolean verifyPass()
{
String pass=editPass.getEditText().getText().toString().trim();
if(pass.isEmpty())
{ editPass.setErrorEnabled(true);
editPass.setError(" Password Required");
return true;
}
else
{
editPass.setErrorEnabled(false);
return false;
}
}
private boolean verifyPass1()
{
String pass1=editPass1.getEditText().getText().toString().trim();
String pass=editPass.getEditText().getText().toString().trim();
if(pass1.isEmpty())
{ editPass1.setErrorEnabled(true);
editPass1.setError("Confirm Password Required");
return true;
}
else if(pass.equals(pass1))
{
editPass1.setErrorEnabled(false);
return false;
}
else
{
editPass1.setErrorEnabled(true);
editPass1.setError("Passwords do not match");
return true;
}
}
private boolean verifyType()
{
if (type.equals("Select Account Type"))
{
Toast.makeText(this, "Please select account type !", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
private boolean verifyCard1()
{
db.collection("User").whereEqualTo("card",Integer.parseInt(editCardNo.getEditText().getText().toString().trim())).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
temp=task.getResult().size();
}
}
});
if(temp==0)
return false;
else
return true;
}
private void registerUser()
{
if(verifyType())
return;
if(type.equals("User"))
{
boolean res= (verifyName()|verifyCardNo()|verifyEmailId()|verifyEnrollNo()|verifyPass()|verifyPass1());
if(res==true)
return;
}
if(type.equals("Admin"))
{
boolean res= (verifyName()|verifyEmailId()|verifyPass()|verifyPass1());
if(res==true)
return;
}
String id=editID.getEditText().getText().toString().trim();
String pass=editPass.getEditText().getText().toString().trim();
if(type.equals("User")){
type1=0;
}
else
type1=1;
progressDialog.setMessage("Registering User ... ");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(id,pass).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
String id=editID.getEditText().getText().toString().trim();
String name=editName.getEditText().getText().toString().trim();
if(type1==0)
{
int enroll=Integer.parseInt(editEnrollNo.getEditText().getText().toString().trim());
int card=Integer.parseInt(editCardNo.getEditText().getText().toString().trim());
db.collection("User").document(id).set(new User(name,id,enroll,card,type1)).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.cancel();
Toast.makeText(SignUpActivity.this,"Registered Successfully !",Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignUpActivity.this, "Please Try Again !", Toast.LENGTH_SHORT).show();
}
});
}
else {
db.collection("User").document(id).set(new Admin(type1,name,id)).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.cancel();
Toast.makeText(SignUpActivity.this,"Registered Successfully !",Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignUpActivity.this, "Please Try Again !", Toast.LENGTH_SHORT).show();
}
});
}
}
else
{ progressDialog.cancel();
if(task.getException() instanceof FirebaseAuthUserCollisionException)
{
Toast.makeText(SignUpActivity.this,"Already Registered ! ",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignUpActivity.this, "Registration Failed ! Try Again ", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
public void onClick(View v) {
if(v==check1)
{
if(check1.isChecked())
buttonRegister.setEnabled(true);
else
buttonRegister.setEnabled(false);
}
else if(v==buttonRegister)
registerUser();
else if(v==toSignIn) {
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}
}
Please can any one help?
When you return from a function, the code written after is never executed. In your method registerUser() every if condition that is true, returns. That means the actual code to register user is never reached.

how to stop MediaPlayer on adapter when CardStackView on Activity Swiped?

i create a MediaPlayer on adapter , when user click image it start.
public class ViewHolder extends RecyclerView.ViewHolder {
RoundedImageView imageView;
TextView username;
ImageButton buttonInfo;
public ViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.itemCardStackView);
username = itemView.findViewById(R.id.textViewUsername_stackView);
buttonInfo = itemView.findViewById(R.id.buttonToInfo_stackView);
}
void setData(Users data) {
mediaPlayer = new MediaPlayer();
if (!data.getAudioIntro().equals("")) {
try {
mediaPlayer.setDataSource(data.getAudioIntro());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "no voiceintro", Toast.LENGTH_SHORT).show();
}
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogPreviewInfo dialogPreviewInfo = new DialogPreviewInfo();
Bundle bundle = new Bundle();
bundle.putString("uid", data.getMyUid());
dialogPreviewInfo.setArguments(bundle);
dialogPreviewInfo.show(((FragmentActivity) context).getSupportFragmentManager(), "tag");
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!data.getAudioIntro().equals("")) {
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
else {
mediaPlayer.start();
}
}
}
});
}
it work,but i want when user swiped imageView , it stop and release MediaPlayer.i know how to use interface pass data from adapter to acivity,but opposite , i don't.
This is my code on activity for CardStackView
manager = new CardStackLayoutManager(getContext(), new CardStackListener() {
#Override
public void onCardDragging(Direction direction, float ratio) {
}
#Override
public void onCardSwiped(Direction direction) {
Log.d(TAG, "onCardSwiped: p=" + manager.getTopPosition() + " d=" + direction);
if (direction == Direction.Right) {
Toast.makeText(getContext(), "Direction Right", Toast.LENGTH_SHORT).show();
}
if (direction == Direction.Top) {
Toast.makeText(getContext(), "Direction Top", Toast.LENGTH_SHORT).show();
}
if (direction == Direction.Left) {
Toast.makeText(getContext(), "Direction Left", Toast.LENGTH_SHORT).show();
}
if (direction == Direction.Bottom) {
Toast.makeText(getContext(), "Direction Bottom", Toast.LENGTH_SHORT).show();
}
if (manager.getTopPosition() == adapter.getItemCount() - 5){
paginate();
}
}
#Override
public void onCardRewound() {
Log.d(TAG, "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardCanceled() {
Log.d(TAG, "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardAppeared(View view, int position) {
Log.d(TAG, "onCardAppeared: " + position);
}
#Override
public void onCardDisappeared(View view, int position) {
Log.d(TAG, "onCardAppeared: " + position);
}
});
manager.setStackFrom(StackFrom.None);
manager.setVisibleCount(3);
manager.setTranslationInterval(20.0f);
manager.setScaleInterval(0.95f);
manager.setSwipeThreshold(0.1f);
manager.setMaxDegree(20.0f);
manager.setDirections(Direction.FREEDOM);
manager.setCanScrollHorizontal(true);
manager.setCanScrollVertical(true);
manager.setSwipeableMethod(SwipeableMethod.AutomaticAndManual);
adapter = new CardStackAdapter(getContext(), listUser, this);
binding.cardStackView.setLayoutManager(manager);
binding.cardStackView.setAdapter(adapter);
binding.cardStackView.setItemAnimator(new DefaultItemAnimator());
can anyone help me , please!
have a nice day,everyone!

How to delete messages from firebase Database?

I am working on a chat application connected to firebase. I am trying to add a future where I can delete a message. This is what I have tried but it's not working.
This is the code
...package com.sollie.ian.eunice.ui
public class ChatActivity extends AppCompatActivity {
private RecyclerView recyclerChat;
public static final int VIEW_TYPE_USER_MESSAGE = 0;
public static final int VIEW_TYPE_FRIEND_MESSAGE = 1;
private ListMessageAdapter adapter;
public String roomId;
private ArrayList<CharSequence> idFriend;
private Consersation consersation;
private MessageInput editWriteMessage;
private LinearLayoutManager linearLayoutManager;
public static HashMap<String, Bitmap> bitmapAvataFriend;
public Bitmap bitmapAvataUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intentData = getIntent();
idFriend = intentData.getCharSequenceArrayListExtra(StaticConfig.INTENT_KEY_CHAT_ID);
roomId = intentData.getStringExtra(StaticConfig.INTENT_KEY_CHAT_ROOM_ID);
String nameFriend = intentData.getStringExtra(StaticConfig.INTENT_KEY_CHAT_FRIEND);
consersation = new Consersation();
String base64AvataUser = SharedPreferenceHelper.getInstance(this).getUserInfo().avata;
if (!base64AvataUser.equals(StaticConfig.STR_DEFAULT_BASE64)) {
byte[] decodedString = Base64.decode(base64AvataUser, Base64.DEFAULT);
bitmapAvataUser = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
} else {
bitmapAvataUser = null;
}
editWriteMessage = findViewById(R.id.input);
if (idFriend != null && nameFriend != null) {
getSupportActionBar().setTitle(nameFriend);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerChat = findViewById(R.id.recyclerChat);
recyclerChat.setLayoutManager(linearLayoutManager);
adapter = new ListMessageAdapter(this, consersation, bitmapAvataFriend, bitmapAvataUser);
FirebaseDatabase.getInstance().getReference().child("message/" + roomId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getValue() != null) {
HashMap mapMessage = (HashMap) dataSnapshot.getValue();
Message newMessage = new Message();
newMessage.idSender = (String) mapMessage.get("idSender");
newMessage.idReceiver = (String) mapMessage.get("idReceiver");
newMessage.text = (String) mapMessage.get("text");
newMessage.timestamp = (long) mapMessage.get("timestamp");
consersation.getListMessageData().add(newMessage);
adapter.notifyDataSetChanged();
linearLayoutManager.scrollToPosition(consersation.getListMessageData().size() - 1);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
recyclerChat.setAdapter(adapter);
}
editWriteMessage.setInputListener(input -> {
String content = input.toString().trim();
if (content.length() > 0) {
// editWriteMessage.setTex("");
Message newMessage = new Message();
newMessage.text = content;
newMessage.idSender = StaticConfig.UID;
newMessage.idReceiver = roomId;
newMessage.timestamp = System.currentTimeMillis();
FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
}
return true;
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home){
Intent result = new Intent();
result.putExtra("idFriend", idFriend.get(0));
setResult(RESULT_OK, result);
this.finish();
}
return true;
}
#Override
public void onBackPressed() {
Intent result = new Intent();
result.putExtra("idFriend", idFriend.get(0));
setResult(RESULT_OK, result);
this.finish();
}
}
class ListMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private Consersation consersation;
private HashMap<String, Bitmap> bitmapAvata;
private HashMap<String, DatabaseReference> bitmapAvataDB;
private Bitmap bitmapAvataUser;
private String roomId;
public ListMessageAdapter(Context context, Consersation consersation, HashMap<String, Bitmap> bitmapAvata, Bitmap bitmapAvataUser) {
this.context = context;
this.consersation = consersation;
this.bitmapAvata = bitmapAvata;
this.bitmapAvataUser = bitmapAvataUser;
bitmapAvataDB = new HashMap<>();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ChatActivity.VIEW_TYPE_FRIEND_MESSAGE) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_friend, parent, false);
return new ItemMessageFriendHolder(view);
} else if (viewType == ChatActivity.VIEW_TYPE_USER_MESSAGE) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_user, parent, false);
return new ItemMessageUserHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ItemMessageFriendHolder) {
((ItemMessageFriendHolder) holder).txtContent.setText(consersation.getListMessageData().get(position).text);
Bitmap currentAvata = bitmapAvata.get(consersation.getListMessageData().get(position).idSender);
if (currentAvata != null) {
((ItemMessageFriendHolder) holder).avata.setImageBitmap(currentAvata);
} else {
final String id = consersation.getListMessageData().get(position).idSender;
if(bitmapAvataDB.get(id) == null){
bitmapAvataDB.put(id, FirebaseDatabase.getInstance().getReference().child("user/" + id + "/avata"));
bitmapAvataDB.get(id).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
String avataStr = (String) dataSnapshot.getValue();
if(!avataStr.equals(StaticConfig.STR_DEFAULT_BASE64)) {
byte[] decodedString = Base64.decode(avataStr, Base64.DEFAULT);
ChatActivity.bitmapAvataFriend.put(id, BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
}else{
ChatActivity.bitmapAvataFriend.put(id, BitmapFactory.decodeResource(context.getResources(), R.drawable.default_avata));
}
notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
} else if (holder instanceof ItemMessageUserHolder) {
((ItemMessageUserHolder) holder).txtContent.setText(consersation.getListMessageData().get(position).text);
if (bitmapAvataUser != null) {
((ItemMessageUserHolder) holder).avata.setImageBitmap(bitmapAvataUser);
}
((ItemMessageUserHolder) holder).txtContent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete Message");
builder.setMessage("Are You Sure To Delete This Messgae");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteMsg(position);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
return false;
}
});
}
}
private void deleteMsg(int position) {
final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String msgtimestmp =String.valueOf(consersation.getListMessageData().get(position).timestamp);
String message=consersation.getListMessageData().get(position).text;
DatabaseReference roofRef=FirebaseDatabase.getInstance().getReference();
roofRef.child("message").child(message)
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(context, "deleted", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemViewType(int position) {
return consersation.getListMessageData().get(position).idSender.equals(StaticConfig.UID) ? ChatActivity.VIEW_TYPE_USER_MESSAGE : ChatActivity.VIEW_TYPE_FRIEND_MESSAGE;
}
#Override
public int getItemCount() {
return consersation.getListMessageData().size();
}
}
class ItemMessageUserHolder extends RecyclerView.ViewHolder {
public TextView txtContent;
public CircleImageView avata;
public ItemMessageUserHolder(View itemView) {
super(itemView);
txtContent = itemView.findViewById(R.id.textContentUser);
avata = itemView.findViewById(R.id.imageView2);
}
}
class ItemMessageFriendHolder extends RecyclerView.ViewHolder {
public TextView txtContent;
public CircleImageView avata;
public ItemMessageFriendHolder(View itemView) {
super(itemView);
txtContent = itemView.findViewById(R.id.textContentFriend);
avata = itemView.findViewById(R.id.imageView3);
}
}
And this is what I have tried
private void deleteMsg(int position) {
final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String msgtimestmp =String.valueOf(consersation.getListMessageData().get(position).timestamp);
String message=consersation.getListMessageData().get(position).text;
DatabaseReference roofRef=FirebaseDatabase.getInstance().getReference();
roofRef.child("message").child(message)
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(context, "deleted", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
}
}
});
}
What am I doing wrong?
The problem is here:
String message=consersation.getListMessageData().get(position).text;
DatabaseReference roofRef=FirebaseDatabase.getInstance().getReference();
roofRef.child("message").child(message).removeValue()
You're trying to delete the message based on its text, but to delete a node from Firebase you need to know its key.
This means that when you read the messages from the database, you'll need to store dataSnapshot.getKey() for each message (probably as a field in your Message class). Then when you are ready to delete the message, you can get the key from that class and pass it into the database call, with something like:
String key= consersation.getListMessageData().get(position).key; // 👈
DatabaseReference roofRef=FirebaseDatabase.getInstance().getReference();
roofRef.child("message").child(key).removeValue()... // 👈

Debug error :java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.List [duplicate]

This question already has answers here:
Explanation of ClassCastException in Java
(12 answers)
Closed 1 year ago.
Every time I click on a profile in my application, it causes this crash and error and I wanted to know why and try to find it.
The error:
java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.List
at com.example.soulforge.fragments.Profile.lambda$loadBasicData$4$Profile(Profile.java:274)
at com.example.soulforge.fragments.-$$Lambda$Profile$KwoPqF2dchhRaWfrPFWRwwexTfQ.onEvent(Unknown Source:4)
at com.google.firebase.firestore.DocumentReference.lambda$addSnapshotListenerInternal$2(DocumentReference.java:504)
at com.google.firebase.firestore.DocumentReference$$Lambda$3.onEvent(Unknown Source:6)
at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(AsyncEventListener.java:42)
at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
The part of the profile that causes the issue
followersList = (List<Object>) value.get("followers");
followingList = (List<Object>) value.get("following");
and the whole profile.java
public class Profile extends Fragment {
boolean isMyProfile = true;
String uid;
String userUID;
FirestoreRecyclerAdapter<PostImageModel, PostImageHolder> adapter;
private TextView nameTv, toolbarNameTv, statusTv, followingCountTv, followersCountTv, postCountTv;
private CircleImageView profileImage;
private Button followBtn;
private RecyclerView recyclerView;
private LinearLayout countLayout;
private FirebaseUser user;
private ImageButton editProfileBtn;
List<Object> followersList, followingList, followingList_2;
boolean isFollowed;
DocumentReference userRef, myRef;
public Profile() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init(view);
myRef = FirebaseFirestore.getInstance().collection("Users")
.document(user.getUid());
if (IS_SEARCHED_USER) {
isMyProfile = false;
userUID = USER_ID;
loadData();
} else {
isMyProfile = true;
userUID = user.getUid();
}
if (isMyProfile) {
editProfileBtn.setVisibility(View.VISIBLE);
followBtn.setVisibility(View.GONE);
countLayout.setVisibility(View.VISIBLE);
} else {
editProfileBtn.setVisibility(View.GONE);
followBtn.setVisibility(View.VISIBLE);
countLayout.setVisibility(View.GONE);
}
userRef = FirebaseFirestore.getInstance().collection("Users")
.document(userUID);
loadBasicData();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
loadPostImages();
recyclerView.setAdapter(adapter);
clickListener();
}
private void loadData() {
myRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.e("Tag_b", error.getMessage());
return;
}
if (value == null || !value.exists()) {
return;
}
followingList_2 = (List<Object>) value.get("Following");
}
});
}
private void clickListener() {
followBtn.setOnClickListener(v -> {
if (isFollowed) {
followersList.remove(user.getUid());
followingList_2.remove(userUID);
final Map<String, Object> map_2 = new HashMap<>();
map_2.put("following", followingList_2);
Map<String, Object> map = new HashMap<>();
map.put("followers", followersList);
userRef.update(map).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
followBtn.setText("Follow");
myRef.update(map_2).addOnCompleteListener(task1 -> {
if (task1.isSuccessful()) {
Toast.makeText(getContext(), "UnFollowed", Toast.LENGTH_SHORT).show();
} else {
Log.e("Tag_3", task1.getException().getMessage());
}
});
} else {
Log.e("Tag", "" + task.getException().getMessage());
}
});
} else {
followersList.add(user.getUid());
followingList_2.add(userUID);
Map<String, Object> map_2 = new HashMap<>();
map_2.put("following", followingList_2);
Map<String, Object> map = new HashMap<>();
map.put("followers", followersList);
userRef.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
followBtn.setText("UnFollow");
myRef.update(map_2).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Followed", Toast.LENGTH_SHORT).show();
} else {
Log.e("Tag", " " + task.getException().getMessage());
}
}
});
} else {
Log.e("Tag", "" + task.getException().getMessage());
}
}
});
}
});
editProfileBtn.setOnClickListener(v -> {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(requireContext(), Profile.this);
});
}
private void init(View view) {
Toolbar toolbar = view.findViewById(R.id.toolbar);
assert getActivity() != null;
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
nameTv = view.findViewById(R.id.nameTv);
toolbarNameTv = view.findViewById(R.id.toolbarNameTV);
statusTv = view.findViewById(R.id.statusTv);
followersCountTv = view.findViewById(R.id.followersCountTv);
followingCountTv = view.findViewById(R.id.followingCountTv);
postCountTv = view.findViewById(R.id.postCountTv);
profileImage = view.findViewById(R.id.profileImage);
followBtn = view.findViewById(R.id.followBtn);
recyclerView = view.findViewById(R.id.recyclerView);
countLayout = view.findViewById(R.id.countLayout);
editProfileBtn = view.findViewById(R.id.edit_profileImage);
FirebaseAuth auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
}
private void loadBasicData() {
userRef.addSnapshotListener((value, error) -> {
if (error != null) {
Log.e("Tag_0", error.getMessage());
return;
}
assert value != null;
if (value.exists()) {
String name = value.getString("name");
String status = value.getString("status");
String profileURL = value.getString("profileImage");
nameTv.setText(name);
toolbarNameTv.setText(name);
statusTv.setText(status);
followersList = (List<Object>) value.get("followers");
followingList = (List<Object>) value.get("following");
followersCountTv.setText("" + followersList.size());
followingCountTv.setText("" + followingList.size());
try {
Glide.with(getContext().getApplicationContext())
.load(profileURL)
.placeholder(R.drawable.ic_person)
.timeout(6500)
.into(profileImage);
} catch (Exception e) {
e.printStackTrace();
}
if (followingList.contains(userUID)) {
followBtn.setText("UnFollow");
isFollowed = true;
} else {
isFollowed = false;
followBtn.setText("Follow");
}
}
});
postCountTv.setText("" + LIST_SIZE);
}
private void loadPostImages() {
DocumentReference reference = FirebaseFirestore.getInstance().collection("Users").document(userUID);
Query query = reference.collection("Post Images");
FirestoreRecyclerOptions<PostImageModel> options = new FirestoreRecyclerOptions.Builder<PostImageModel>()
.setQuery(query, PostImageModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<PostImageModel, PostImageHolder>(options) {
#NonNull
#Override
public PostImageHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.profile_image_items, parent, false);
return new PostImageHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull PostImageHolder holder, int position, #NonNull PostImageModel model) {
Glide.with(holder.itemView.getContext().getApplicationContext())
.load(model.getImageUrl())
.timeout(6500)
.into(holder.imageView);
}
};
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri uri = result.getUri();
uploadImage(uri);
}
}
private void uploadImage(Uri uri) {
StorageReference reference = FirebaseStorage.getInstance().getReference().child("Profile Images");
reference.putFile(uri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String imageURL = uri.toString();
UserProfileChangeRequest.Builder request = new UserProfileChangeRequest.Builder();
request.setPhotoUri(uri);
user.updateProfile(request.build());
Map<String, Object> map = new HashMap<>();
map.put("profileImage", imageURL);
map.put("date", FieldValue.serverTimestamp());
FirebaseFirestore.getInstance().collection("Users")
.document(user.getUid())
.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
Toast.makeText(getContext(), "Updated Successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext(), "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
} else {
Toast.makeText(getContext(), "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private static class PostImageHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
public PostImageHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
Why is this happening ,and why is it a Long instead of being a list and causing all this issues?
The problem is that the data is of Long class and you are trying to cast it to List
What you should try is
Map<String, Object> followerMap= new HashMap<>();
followerMap= value.getData();
assert followerMap!= null;
for (Map.Entry<String, Object> e : followerMap.entrySet()) {
long following= e.getValue();
followingList_2 .add(following);
}

how to solve catch or finally expected error? [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 4 years ago.
Improve this question
How to solve "'catch' or 'finally' expected" error in android studio..?
a screenshot of the error
public class FragmentRecent extends Fragment {
View root_view, parent_view;
private RecyclerView recyclerView;
private AdapterChannel adapterChannel;
private SwipeRefreshLayout swipeRefreshLayout;
private Call<CallbackChannel> callbackCall = null;
private int post_total = 0;
private int failed_page = 0;
private InterstitialAd interstitialAd;
private OfflineDatabase databaseHelper;
int counter = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_recent, null);
parent_view = getActivity().findViewById(R.id.main_content);
loadInterstitialAd();
swipeRefreshLayout = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_home);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
adapterChannel = new AdapterChannel(getActivity(), recyclerView, new ArrayList<Channel>());
recyclerView.setAdapter(adapterChannel);
// on item list clicked
adapterChannel.setOnItemClickListener(new AdapterChannel.OnItemClickListener() {
#Override
public void onItemClick(View v, Channel obj, int position) {
Intent intent = new Intent(getActivity(), ActivityDetailChannel.class);
intent.putExtra(Constant.KEY_CHANNEL_CATEGORY, obj.category_name);
intent.putExtra(Constant.KEY_CHANNEL_ID, obj.channel_id);
intent.putExtra(Constant.KEY_CHANNEL_NAME, obj.channel_name);
intent.putExtra(Constant.KEY_CHANNEL_IMAGE, obj.channel_image);
intent.putExtra(Constant.KEY_CHANNEL_URL, obj.channel_url);
intent.putExtra(Constant.KEY_CHANNEL_DESCRIPTION, obj.channel_description);
startActivity(intent);
showInterstitialAd();
}
});
// detect when scroll reach bottom
adapterChannel.setOnLoadMoreListener(new AdapterChannel.OnLoadMoreListener() {
#Override
public void onLoadMore(int current_page) {
if (post_total > adapterChannel.getItemCount() && current_page != 0) {
int next_page = current_page + 1;
requestAction(next_page);
} else {
adapterChannel.setLoaded();
}
}
});
// on swipe list
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
adapterChannel.resetListData();
requestAction(1);
}
});
requestAction(1);
return root_view;
}
private void displayApiResult(final List<Channel> channels) {
adapterChannel.insertData(channels);
swipeProgress(false);
if (channels.size() == 0) {
showNoItemView(true);
}
}
private void requestListPostApi(final int page_no) {
ApiInterface apiInterface = RestAdapter.createAPI();
callbackCall = apiInterface.getPostByPage(page_no, Config.LOAD_MORE);
callbackCall.enqueue(new Callback<CallbackChannel>() {
#Override
public void onResponse(Call<CallbackChannel> call, Response<CallbackChannel> response) {
CallbackChannel resp = response.body();
if (resp != null && resp.status.equals("ok")) {
post_total = resp.count_total;
displayApiResult(resp.posts);
} else {
onFailRequest(page_no);
}
}
#Override
public void onFailure(Call<CallbackChannel> call, Throwable t) {
if (!call.isCanceled()) onFailRequest(page_no);
}
});
}
private void onFailRequest(int page_no) {
failed_page = page_no;
adapterChannel.setLoaded();
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
} else {
//showToast("Internet Not");
if (databaseHelper.getOfflineData("FragmentCategory").length() != 0) {
setJson(databaseHelper.getOfflineData("FragmentCategory"), false);
}
}
}
//databaseHelper.removeAll();
private void requestAction(final int page_no) {
showFailedView(false, "");
showNoItemView(false);
if (page_no == 1) {
swipeProgress(true);
} else {
adapterChannel.setLoading();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestListPostApi(page_no);
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if (callbackCall != null && callbackCall.isExecuted()) {
callbackCall.cancel();
}
}
private void showFailedView(boolean show, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_home);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction(failed_page);
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_home);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_post_found);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
return;
}
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(show);
}
});
}
public void setJson(String result, Boolean isOnline) {
try {
//inseting result to database
if(isOnline) {
ContentValues offline_data = new ContentValues();
offline_data.put(OfflineDatabase.KEY_OFFLINE_DATA, result);
if(databaseHelper.getOfflineData("FragmentCategory").length()!=0) {
databaseHelper.update("FragmentCategory",offline_data);
} else {
offline_data.put(OfflineDatabase.KEY_ACTIVITY_NAME, "FragmentCategory");
databaseHelper.addOfflineData(offline_data, null);
//handle both exceptions
}
}}}
private void loadInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
interstitialAd = new InterstitialAd(getActivity());
interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id));
interstitialAd.loadAd(new AdRequest.Builder().build());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
interstitialAd.loadAd(new AdRequest.Builder().build());
}
});
} else {
Log.d("AdMob", "AdMob Interstitial is Enabled");
}
}
private void showInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
if (interstitialAd != null && interstitialAd.isLoaded()) {
if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) {
interstitialAd.show();
counter = 1;
} else {
counter++;
}
} else {
Log.d("AdMob", "Interstitial Ad is Disabled");
}
} else {
Log.d("AdMob", "AdMob Interstitial is Disabled");
}
}}
there you start with try:
public void setJson(String result, Boolean isOnline) {
try {
...
}
...
}
which has to continue with:
try {
...
} catch(Exception e) {
} finally {
}
where either catch or finally are optional (depending where the Exception shall be handled).

Categories