error for retrieving an images from firebase - java

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

Related

remain same position like button in recyclerview android

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

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.

on back pressed I want to go previous activity from adapter

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

Firebase storage: Allow authenticated users to download files

I have limited the storage of firebase, to only allow authenticated users to read and write from Firebase console. All my project requests are working except the download page of PDF files. I'm suspecting i didn't add the authentication listener in the correct way.
This is my code for my Adapter and my Activity:
Download Activity:
public class pdfDownloader extends AppCompatActivity {
FirebaseFirestore db;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListner;
FirebaseUser mUser;
RecyclerView mRecyclerView;
ArrayList<DownModel> downModelArrayList = new ArrayList<>();
MyPdfAdapter myAdapter;
public static final String TAG="LOGIN";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_downloader);
mAuth = FirebaseAuth.getInstance();
mUser = FirebaseAuth.getInstance().getCurrentUser();
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(mUser != null) {
dataFromFirebase();
} else {
Log.d(TAG,"AuthStateChanged:Logout");
}
}
};
setUpRV();
setUpFB();
dataFromFirebase();
}
protected void onStart() { // allowing users to see the links
super.onStart();
if(mUser == null) {
dataFromFirebase();
} else {
Log.d(TAG,"AuthStateChanged:Logout");
}
}
private void dataFromFirebase() {
if(downModelArrayList.size() > 0)
downModelArrayList.clear();
db.collection("files")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for(DocumentSnapshot documentSnapshot: Objects.requireNonNull(task.getResult())) {
DownModel downModel= new DownModel(documentSnapshot.getString("name"),
documentSnapshot.getString("link"));
downModelArrayList.add(downModel);
}
myAdapter= new MyPdfAdapter(pdfDownloader.this,downModelArrayList);
mRecyclerView.setAdapter(myAdapter);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(pdfDownloader.this, "Error ;-.-;", Toast.LENGTH_SHORT).show();
}
});
}
private void setUpFB(){
db = FirebaseFirestore.getInstance();
}
private void setUpRV(){
mRecyclerView= findViewById(R.id.recycle);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
Download Adapter:
public class MyPdfAdapter extends RecyclerView.Adapter<MyViewHolder> {
pdfDownloader pdfDownloader;
ArrayList<DownModel> downModels;
FirebaseFirestore db;
public MyPdfAdapter(pdfDownloader pdfDownloader, ArrayList<DownModel> downModels) {
this.pdfDownloader = pdfDownloader;
this.downModels = downModels;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(pdfDownloader.getBaseContext());
View view = layoutInflater.inflate(R.layout.elements, null, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, final int i) {
myViewHolder.mName.setText(downModels.get(i).getName());
myViewHolder.mLink.setText(downModels.get(i).getLink());
myViewHolder.deletePdfBtn.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
deletepdf();
}
});
myViewHolder.mDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadFile(myViewHolder.mName.getContext(),downModels.get(i).getName(), ".pdf", DIRECTORY_DOWNLOADS,downModels.get(i).getLink());
}
});
}
private void deletepdf() {
db.collection( "files" ).document()
.delete()
.addOnSuccessListener( new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
} );
}
public void downloadFile(Context context, String fileName, String fileExtension, String destinationDirectory, String url) {
DownloadManager downloadmanager = (DownloadManager) context.
getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName + fileExtension);
downloadmanager.enqueue(request);
}
#Override
public int getItemCount() {
return downModels.size();
}
}
This solved my problem:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}

Recyclerview not scrolling to saved position after screen rotation

Hi I want to save Recylerview scroll position when screen rotates so that Recyclerview scrolls to that position before user sees screen.
I have tried every possible solution so far for similar questions but nothing is working. I am using GridLayoutManager with Recyclerview and displaying grid list of movies using JSON data.
Please have a look!!
MainActivity:
public class MainActivity extends AppCompatActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
private RecyclerView recyclerView;
private ArrayList<Movie> movieList;
MovieAdapter adapter;
private final String KEY_RECYCLER_STATE = "recycler_state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
movieList = new ArrayList<>();
adapter = new MovieAdapter(this, movieList);
/*
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
}
*/
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setAdapter(adapter);
checkSort();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_RECYCLER_STATE, recyclerView.getLayoutManager().onSaveInstanceState());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState != null)
{
Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(KEY_RECYCLER_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);
}
}
public Activity getActivity() {
Context context = this;
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
private void JSONMostPopularMovie() {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(getApplicationContext(), "There Is No API Key!", Toast.LENGTH_SHORT).show();
return;
}
MovieApi movieapi = new MovieApi();
MovieService apiService = MovieApi.getClient().create(MovieService.class);
Call<MovieResponse> call = apiService.getPopularMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
ArrayList<Movie> movies = response.body().getResults();
adapter.setMovies(movies);
Toast.makeText(MainActivity.this, "Displaying By Most Popular Movies", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d("Error", "" + t.getMessage());
Toast.makeText(MainActivity.this, "Error Fetching Data! And Internet Connection", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
private void JSONTopRateMovie() {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(getApplicationContext(), "There Is No API Key", Toast.LENGTH_SHORT).show();
return;
}
MovieApi movieapi = new MovieApi();
MovieService apiService = MovieApi.getClient().create(MovieService.class);
Call<MovieResponse> call = apiService.getTopRatedMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
ArrayList<Movie> movies = response.body().getResults();
adapter.setMovies(movies);
Toast.makeText(MainActivity.this, "Displaying By Top Rated Movies", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d("Error", "" + t.getMessage());
Toast.makeText(MainActivity.this, "Error Fetching Data! And Internet Connection", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent setting = new Intent(this, MovieSettings.class);
startActivity(setting);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
checkSort();
}
private void checkSort() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortOrder = preferences.getString(
this.getString(R.string.pref_sort_order_key),
this.getString(R.string.pref_most_popular)
);
if (sortOrder.equals(this.getString(R.string.pref_most_popular))) {
Log.d(LOG_TAG, "Sorting by most popular");
JSONMostPopularMovie();
} else if (sortOrder.equals(this.getString(R.string.top_rated))) {
Log.d(LOG_TAG, "Sorting by top rated");
JSONTopRateMovie();
}
}
}
Adapter:
public class MovieAdapter extends
RecyclerView.Adapter<MovieAdapter.MyViewHolder> {
private Context mContext;
private ArrayList<Movie> movieList;
public MovieAdapter(Context mContext, ArrayList<Movie> movieList) {
this.mContext = mContext;
this.movieList = movieList;
}
#Override
public MovieAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.movie_item, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MovieAdapter.MyViewHolder viewHolder, int i) {
viewHolder.title.setText(movieList.get(i).getOriginalTitle());
String vote = Double.toString(movieList.get(i).getVoteAverage());
viewHolder.userrating.setText(vote);
String poster = "https://image.tmdb.org/t/p/w185/" + movieList.get(i).getPosterPath();
Picasso.with(mContext)
.load(poster)
.into(viewHolder.thumbnail);
}
#Override
public int getItemCount() {
return movieList.size();
}
public void setMovies(ArrayList<Movie> movies){
this.movieList = movies;
notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, userrating;
public ImageView thumbnail;
public MyViewHolder(final View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
userrating = (TextView) view.findViewById(R.id.userrating);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Intent intent = new Intent(mContext, MovieDetail.class);
intent.putExtra("movie", movieList.get(position));
intent.putExtra("id", movieList.get(position).getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
});
}
}
}

Categories

Resources