ViewPager2 adapter item layout flattened - android-layout

I'm facing an issue with my viewpager2 adapter. The adapter contains a share button which starts an new activity with a create chooser Intent. The problem is if swipe down or press the android back button the current item layout is flattened or sometime it changes the current item to the next one.
However if go through the sharing process completely the app works fine.
ViewPager2.JAVA*
public class StreamPostDetailAdapter extends RecyclerView.Adapter<StreamPostDetailAdapter.TestPagerViewHolder> {
public Context mContext;
public List<Post> mPost;
private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String mUid ;
public IpagerAdapter mListener;
private CommentAdapter commentAdapter;
private List<Comment> commentList;
public StreamPostDetailAdapter(Context mContext, List<Post> mPost, IpagerAdapter mListener) {
this.mListener = mListener;
this.mContext = mContext;
this.mPost = mPost;
mUid = firebaseUser.getUid();
}
#NonNull
#Override
public TestPagerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_post_swipe_item, parent, false);
return new TestPagerViewHolder(view,mListener);
}
#Override
public void onBindViewHolder(#NonNull TestPagerViewHolder holder, int position) {
Post post = mPost.get(holder.getBindingAdapterPosition());
String post_publisher = post.getPublisher();
String post_id = post.getPostid() ;
String post_image = post.getPostimage() ;
String post_timeStamp = post.getTimestamp();
String tag_list = post.getTagList();
String postTitle = post.getDescription();
boolean personal = post.getPersonal_tattoo();
commentList = new ArrayList<>();
commentAdapter = new CommentAdapter(mContext,commentList);
GlideApp.with(mContext).load(post_image)
.placeholder(R.mipmap.loading_img_placeholder)
.into(holder.image_post);
holder.title.setText(post.getDescription());
if (post.getTagList().equals("")) {
holder.tagList.setVisibility(View.GONE);
} else {
holder.tagList.setVisibility(View.VISIBLE);
holder.tagList.setText(post.getTagList());
}
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.bsCommentsController(post_id, holder.commentRv);
BottomSheetBehavior.from(holder.bsComments).setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).removeValue();
}
}
});
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("id", post_publisher);
editor.apply();
Intent intent = new Intent(mContext,HomeActivity.class);
intent.putExtra("origin","ViewPager");
mContext.startActivity(intent);
((StreamPostDetailActivity)mContext).finish();
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContext instanceof SavedPostActivity) {
mListener.removePost(post_id,post_image,position);
}
if (holder.save.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).removeValue();
}
}
});
holder.share_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable drawable = (BitmapDrawable)holder.image_post.getDrawable();
Bitmap bitmap = drawable.getBitmap();
String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, UUID.randomUUID().toString() + ".jpeg", "drawing");
Uri uri = Uri.parse(path);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM,uri);
intent.putExtra(Intent.EXTRA_TEXT, "Playstore Link : put app link in store ");
mContext.startActivity(Intent.createChooser(intent,"Share2"));
}
});
if (mContext instanceof SearchTattooDetailsActivity) {
holder.btn_post_options.setVisibility(View.GONE);
}else {
holder.btn_post_options.setVisibility(View.VISIBLE);
holder.btn_post_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMoreOptions(holder.btn_post_options, post_publisher, mUid, post_id, post_image, position, postTitle
, tag_list, personal);
}
});
}
// Add a new comment
holder.sendComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!holder.comment_bar_edt.getText().toString().equals("")){
mListener.addComment(post_id, holder.comment_bar_edt.getText().toString());
holder.comment_bar_edt.setText("");
holder.comment_bar_edt.clearFocus();
}
}
});
holder.commentRv.setHasFixedSize(true);
holder.commentRv.setAdapter(commentAdapter);
}
#Override
public int getItemCount() {
return mPost.size();
}
private void showMoreOptions(ImageButton btn_post_options, String post_publisher, String mUid, String post_id, String post_image,int posItem, String postTitle, String tagList, boolean personal) {
PopupMenu popupMenu = new PopupMenu(mContext,btn_post_options, Gravity.END);
if (!post_publisher.equals(mUid)) {
popupMenu.getMenu().add(Menu.NONE,0,0,"Report post");
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == 0){
Toast.makeText(mContext, "CreateReportPost/UserNewCategoryRequestEmail", Toast.LENGTH_SHORT).show();
} else if (id == 1) {
//not working
Intent intentEdit = new Intent(mContext, EditPostActivity.class);
intentEdit.putExtra("title",postTitle);
intentEdit.putExtra("imageUrl", post_image);
intentEdit.putExtra("tagList", tagList );
intentEdit.putExtra("personal", personal );
intentEdit.putExtra("postId", post_id);
intentEdit.putExtra("posEditedPost", posItem);
((Activity)mContext).finish();
mContext.startActivity(intentEdit);
}
return false;
}
});
popupMenu.show();
}
//View Holder Class
public static class TestPagerViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, image_post, like, comment, save,share_post;
public TextView username, likes, comments, title, time,tagList;
public ImageButton btn_post_options;
public IpagerAdapter mListener;
//Comments Bottom sheet
EditText comment_bar_edt;
public RecyclerView commentRv ;
ImageView sendComment,userImgComment;
public ConstraintLayout bsComments;
public LinearLayoutManager layoutManager;
public TestPagerViewHolder(#NonNull View itemView, IpagerAdapter mListener) {
super(itemView);
this.mListener = mListener;
image_post = itemView.findViewById(R.id.post_image);
image_profile = itemView.findViewById(R.id.image_profile);
like = itemView.findViewById(R.id.like_ic);
share_post= itemView.findViewById(R.id.share_post);
comment = itemView.findViewById(R.id.comment_ic);
save = itemView.findViewById(R.id.save);
username = itemView.findViewById(R.id.username);
likes = itemView.findViewById(R.id.likes);
comments = itemView.findViewById(R.id.comments);
tagList = itemView.findViewById(R.id.tagList);
title = itemView.findViewById(R.id.title);
time = itemView.findViewById(R.id.time);
btn_post_options = itemView.findViewById(R.id.post_options);
bsComments= itemView.findViewById(R.id.bsComments);
comment_bar_edt = itemView.findViewById(R.id.comment_bar_edt);
sendComment = itemView.findViewById(R.id.sendComment);
commentRv = itemView.findViewById(R.id.comments_rv);
BottomSheetBehavior.from(bsComments).setState(BottomSheetBehavior.STATE_HIDDEN);
}
}
public interface IpagerAdapter {
void removePost(String post_id, String post_image, int position);
void bsCommentsController(String post_id, RecyclerView commentRecyclerView);
void addComment(String post_id,String comment_txt);
}
public void removeItem(int position) {
if (position > -1 && position < mPost.size()) {
mPost.remove(position);
notifyDataSetChanged();
notifyItemRemoved(position);
}
}
}

#Francis,
Since It has been a while, I just remember that I've made changes in how I handled the BottomSheet which was containing the Comments RecyclerView. I extracted it from the StreamPostDetailAdapter (ViewPager2) and moved it to the corresponding activity. Therefore I have only one BottomSheet for all viewpager2 items. Then recyclerView data (comments fetch from firebase) is updated using interface listener methods to populate each items.
You will find the code of the ViewPager2 below:
public class StreamPostDetailAdapter extends RecyclerView.Adapter<StreamPostDetailAdapter.TestPagerViewHolder> {
public Context mContext;
public List<Post> mPost;
private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String mUid ;
public IpagerAdapter mListener;
private CommentAdapter commentAdapter;
private List<Comment> commentList;
public StreamPostDetailAdapter(Context mContext, List<Post> mPost, IpagerAdapter mListener) {
this.mListener = mListener;
this.mContext = mContext;
this.mPost = mPost;
mUid = firebaseUser.getUid();
}
#NonNull
#Override
public TestPagerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_post_swipe_item, parent, false);
return new TestPagerViewHolder(view,mListener);
}
#Override
public void onBindViewHolder(#NonNull TestPagerViewHolder holder, int position) {
Post post = mPost.get(holder.getBindingAdapterPosition());
String post_publisher = post.getPublisher();
String post_id = post.getPostid() ;
String post_image = post.getPostimage() ;
String post_timeStamp = post.getTimestamp();
String tag_list = post.getTagList();
String postTitle = post.getDescription();
boolean personal = post.getPersonal_tattoo();
GlideApp.with(mContext).load(post_image)
.placeholder(R.mipmap.loading_img_placeholder)
.into(holder.image_post);
holder.title.setText(post.getDescription());
if (post.getTagList().equals("")) {
holder.tagList.setVisibility(View.GONE);
} else {
holder.tagList.setVisibility(View.VISIBLE);
holder.tagList.setText(post.getTagList());
}
publisherInfo(holder.image_profile, holder.username, post_publisher);
asLiked(post_id, holder.like);
nLikes(holder.likes, post_id);
//getComments(post_id, holder.comments);
isSaved(post_id, holder.save);
getTimeAgo(holder.time, post_timeStamp);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.openBsComment();
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).removeValue();
}
}
});
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("id", post_publisher);
editor.apply();
Intent intent = new Intent(mContext,HomeActivity.class);
intent.putExtra("origin","ViewPager");
mContext.startActivity(intent);
((StreamPostDetailActivity)mContext).finish();
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContext instanceof SavedPostActivity) {
mListener.removePost(post_id,post_image,position);
}
if (holder.save.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).removeValue();
}
}
});
holder.share_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable drawable = (BitmapDrawable)holder.image_post.getDrawable();
Bitmap bitmap = drawable.getBitmap();
mListener.sharePost(bitmap);
}
});
if (mContext instanceof TaggedTattooDetailsActivity) {
holder.btn_post_options.setVisibility(View.GONE);
}else {
holder.btn_post_options.setVisibility(View.VISIBLE);
holder.btn_post_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMoreOptions(holder.btn_post_options, post_publisher, mUid, post_id, post_image, position, postTitle
, tag_list, personal);
}
});
}
// Add a new comment
}
#Override
public int getItemCount() {
return mPost.size();
}
private void showMoreOptions(ImageButton btn_post_options, String post_publisher, String mUid, String post_id, String post_image,int posItem, String postTitle, String tagList, boolean personal) {
PopupMenu popupMenu = new PopupMenu(mContext,btn_post_options, Gravity.END);
if (!post_publisher.equals(mUid)) {
popupMenu.getMenu().add(Menu.NONE,0,0,"Report post");
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == 0){
Toast.makeText(mContext, "CreateReportPost/UserNewCategoryRequestEmail", Toast.LENGTH_SHORT).show();
} else if (id == 1) {
//not working
Intent intentEdit = new Intent(mContext, EditPostActivity.class);
intentEdit.putExtra("title",postTitle);
intentEdit.putExtra("imageUrl", post_image);
intentEdit.putExtra("tagList", tagList );
intentEdit.putExtra("personal", personal );
intentEdit.putExtra("postId", post_id);
intentEdit.putExtra("posEditedPost", posItem);
((Activity)mContext).finish();
mContext.startActivity(intentEdit);
}
return false;
}
});
popupMenu.show();
}
//View Holder Class
public static class TestPagerViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, image_post, like, comment, save,share_post;
public TextView username, likes, comments, title, time,tagList;
public ImageButton btn_post_options;
public IpagerAdapter mListener;
//Comments Bottom sheet
public LinearLayoutManager layoutManager;
public TestPagerViewHolder(#NonNull View itemView, IpagerAdapter mListener) {
super(itemView);
this.mListener = mListener;
image_post = itemView.findViewById(R.id.post_image);
image_profile = itemView.findViewById(R.id.image_profile);
like = itemView.findViewById(R.id.like_ic);
share_post= itemView.findViewById(R.id.share_post);
comment = itemView.findViewById(R.id.comment_ic);
save = itemView.findViewById(R.id.save);
username = itemView.findViewById(R.id.username);
likes = itemView.findViewById(R.id.likes);
comments = itemView.findViewById(R.id.comments);
tagList = itemView.findViewById(R.id.tagList);
title = itemView.findViewById(R.id.title);
time = itemView.findViewById(R.id.time);
btn_post_options = itemView.findViewById(R.id.post_options);
}
}
public interface IpagerAdapter {
void removePost(String post_id, String post_image, int position);
void openBsComment();
void sharePost(Bitmap postImage);
}
private void getComments(String postid, TextView comments) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.getChildrenCount() != 0) {
comments.setText(" " + snapshot.getChildrenCount());
} else {
comments.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void getTimeAgo(TextView time, String stamp_post) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");;
Log.i(TAG, "timestamp value in format date: "+ stamp_post);
try {
long timeStamp = sdf.parse(stamp_post).getTime();
long now = System.currentTimeMillis();
CharSequence ago = DateUtils.getRelativeTimeSpanString(timeStamp, now, DateUtils.MINUTE_IN_MILLIS);
Log.i(TAG, "timestamp milli value is: " + timeStamp);
time.setText(ago);
} catch (ParseException e) {
e.printStackTrace();
}
}
private void asLiked(String postid, final ImageView imageView) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(firebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.liked);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_like);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void nLikes(final TextView likes, String postid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
likes.setText(" "+ snapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void isSaved(String postid, final ImageView imageView) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(postid).exists()) {
imageView.setImageResource(R.drawable.ic_bookmark_colored);
imageView.setTag("saved");
} else {
imageView.setImageResource(R.drawable.ic_save_post);
imageView.setTag("save");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void publisherInfo(ImageView image_profile, TextView username, String userid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("App_users")
.child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
Glide.with(mContext.getApplicationContext()).load(user.getimageUrl()).into(image_profile);
username.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public void removeItem(int position) {
if (position > -1 && position < mPost.size()) {
mPost.remove(position);
notifyDataSetChanged();
notifyItemRemoved(position);
}
}
}

Related

how to get all values added to recyclerview and send it to ion lib

so im trying to get recyclerview data list added and send it to ion lib when i use method below i only get one element as ill have to change string inside for() to String fav =null ouside of for() and log.d only shows the last result. i need get all so i can send to senddata() to ion lib
FavModelClass
private String fav;
private String user_id;
public FavModelClass(String fav, String user_id) {
this.fav = fav;
this.user_id = user_id;
}
public String getFav() {
return fav;
}
public void setFav(String fav) {
this.fav = fav;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
}
adapter
public class FavAdapter extends
RecyclerView.Adapter<FavAdapter .MyViewHolder> {
private List<FavModelClass> favModelClassList;
private Context beddingContext;
public FavAdapter (List<FavModelClass> favModelClassList, Context
beddingContext) {
this.favModelClassList= favModelClassList;
this.beddingContext = beddingContext;
}
#NonNull
#Override
public FavAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amenitylayout,parent,false);
FavAdapter .MyViewHolder holder = new FavAdapter .MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull FavAdapter.MyViewHolder holder, int i) {
final FavModelClassdata = favModelClassList.get(i);
holder.ac_bedding_type.setText(data.getFav()+" "+"MAX:"+data.getUser_id());
holder.delete_entry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeAt(holder.getAdapterPosition());
}
});
}
public void removeAt(int position) {
favModelClassList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, favModelClassList.size());
}
#Override
public int getItemCount() {
return favModelClassList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView ac_bedding_type;
private ImageButton delete_entry;
public MyViewHolder(#NonNull View v) {
super(v);
ac_bedding_type = v.findViewById(R.id.ac_amenity_name);
delete_entry = v.findViewById(R.id.delete_amenity_entry);
}
}
}
Main activity
fav_recycler = findViewById(R.id.fave_recycler);
GridLayoutManager layoutManager1 = new GridLayoutManager(getApplicationContext(), 2,GridLayoutManager.VERTICAL, false);
fav_recycler.setHasFixedSize(true);
fav_recycler.setLayoutManager(layoutManager1);
favModelClassList= new ArrayList<>();
addfavamenity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
favModelClassList.add(new FavModelClass(
amenityET.getText().toString(),
user_idET.getText().toString()
));
amenityET.setText("");
user_idET.setText("");
FavAdapter adapter = new FavAdapter (favModelClassList, getApplicationContext());
adapter.notifyDataSetChanged();
fav_recycler.setAdapter(adapter);
for (int i = 0; i < favModelClassList.size(); i++) {
final FavModelClassList data = favModelClassList.get(i);
final String fav= data.getFav();
final String user_id = data.getUser_id();
Log.d(TAG, "onClick: "+ fav);
}
}
});
ArrayList d = new ArrayList();
for (int i = 0; i < favModelClassList.size(); i++) {
final FavModelClassList data = favModelClassList.get(i);
d.add(data.getFav());
}
Log.d(TAG, "onClick: " + d);

I want to know how to randomly display images in gridview through SwipeRefreshLayout

SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_grid);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImages();
refreshLayout.setRefreshing(false);
}
});
getImages();
}
I want to know how to randomly display images in gridview through SwipeRefreshLayout
I want a UI like the site https://www.pinterest.com
I want to show random images on refresh to show a lot of images, can you tell me how?
thank you in advance
Below is the full code.
public class MainActivity extends AppCompatActivity {
private List<String> mImagesLinks = new ArrayList<>();
private GridView mGridView;
FloatingActionButton option_01;
FloatingActionButton option_02;
FloatingActionButton option_03;
FloatingActionButton option_04;
static final int PERMISSIONS_REQUEST = 0x0000001;
//종료팝업 전면광고 추가
private static final String TAG = "ted";
TedAdmobDialog nativeTedAdmobDialog;
int nCurrentPermission = 0;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getString(R.string.admob_app_id));
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
checkPermission();
mGridView = findViewById(R.id.grid_view);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
startActivity(new Intent(MainActivity.this, ImageActivity.class)
.putExtra("Link", mImagesLinks.get(i)));
}
});
option_01 = findViewById(R.id.option_01);
option_01.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
startActivity(intent);
});
option_02 = findViewById(R.id.option_02);
option_02.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=Project+J+Lab"));
startActivity(intent);
});
option_03 = findViewById(R.id.option_03);
option_03.setOnClickListener(v -> {
Intent myintent = new Intent(Intent.ACTION_SEND);
myintent.setType("text/plan");
String shereBoday = "Your Boday Here";
String shereSub = "\"http://play.google.com/store/apps/details?id=" + getPackageName();
myintent.putExtra(Intent.EXTRA_SUBJECT, shereBoday);
myintent.putExtra(Intent.EXTRA_TEXT, shereSub);
startActivity(Intent.createChooser(myintent, "shere Using"));
});
option_04 = findViewById(R.id.option_04);
option_04.setOnClickListener(v -> {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"dhsthdwjd1#gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, getPackageName());
email.putExtra(Intent.EXTRA_TEXT, "text");
startActivity(email);
});
SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_grid);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImages();
refreshLayout.setRefreshing(false);
}
});
getImages();
}
private void getImages() {
Call<List<String>> imagesResponse = NetworkUtils.getInterface().loadImages();
imagesResponse.enqueue(new Callback<List<String>>() {
#Override
public void onResponse(Call<List<String>> call, Response<List<String>> response) {
if (response.isSuccessful()) {
mImagesLinks = response.body();
ImagesAdapter imagesAdapter = new ImagesAdapter(MainActivity.this, mImagesLinks);
mGridView.setAdapter(imagesAdapter);
imagesAdapter.notifyDataSetChanged();
} else {
Toast.makeText(MainActivity.this, R.string.error_response, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<List<String>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
//종료팝업 전면광고 추가
nativeTedAdmobDialog = new TedAdmobDialog.Builder(MainActivity.this, TedAdmobDialog.AdType.NATIVE, getString(R.string.banner_ad_unit_id_native))
.setOnBackPressListener(new OnBackPressListener() {
#Override
public void onReviewClick() {
}
#Override
public void onFinish() {
finish();
}
#Override
public void onAdShow() {
log("onAdShow");
nativeTedAdmobDialog.loadNative();
}
})
.create();
nativeTedAdmobDialog.show();
}
//종료팝업 전면광고 추가
private void log(String text) {
Log.d(TAG, text);
}
private void checkPermission() {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setPermissions(
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.SET_WALLPAPER,
Manifest.permission.READ_CONTACTS)
.check();
}
}
Just use Collections.shuffle(list); in your getImages() function.
Refer this for more information : https://www.geeksforgeeks.org/shuffle-or-randomize-a-list-in-java/

Adapter does not update

When switching to Detail, the RecyclerView list is not updated, but rather, I get a blank screen when returning as in the picture. I know that when using NavigationUI, Fragment is recreated. In the code below, returning results in ruleAdapter! = Null. There is an idea when you click on the list item and go to Detail to make ruleAdapter = null, but I think this is not true.
public class RuleListFragment extends Fragment {
private RecyclerView recyclerView;
private RuleAdapter ruleAdapter;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateRule();
return view;
}
public void updateRule() {
RuleLab ruleLab = RuleLab.get(getActivity());
List<Rule> rules = ruleLab.getRules();
if (ruleAdapter == null) {
ruleAdapter = new RuleAdapter(rules);
recyclerView.setAdapter(ruleAdapter);
} else {
ruleAdapter.setRules(rules);
ruleAdapter.notifyDataSetChanged();
}
}
private class RuleHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Rule rule;
private ImageView ruleIcon;
private TextView ruleTitle;
private ImageButton ruleElect;
private RuleHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
ruleIcon = itemView.findViewById(R.id.ruleIcon);
ruleTitle = itemView.findViewById(R.id.ruleTitle);
ruleElect = itemView.findViewById(R.id.ruleElect);
ruleElect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean elect = !rule.isElect();
rule.setElect(elect);
RuleLab.get(getActivity()).updateRule(rule);
if (elect) {
ruleElect.setImageResource(R.drawable.ic_elect_on);
} else {
ruleElect.setImageResource(R.drawable.ic_elect_off);
}
updateRule();
}
});
}
private void bind (Rule rule) {
this.rule = rule;
int iconId = getResources().getIdentifier(rule.getIcon(), "drawable", getActivity().getPackageName());
ruleIcon.setImageResource(iconId);
ruleTitle.setText(rule.getTitle());
ruleElect.setImageResource(rule.isElect() ? R.drawable.ic_elect_on : R.drawable.ic_elect_off);
}
#Override
public void onClick(View view) {
Bundle args = new Bundle();
args.putSerializable("ruleId", rule.getId());
Navigation.findNavController(view).navigate(R.id.ruleFragment, args);
}
}
private class RuleAdapter extends RecyclerView.Adapter<RuleHolder> {
private List<Rule> rules;
private RuleAdapter (List<Rule> rules) {
this.rules = rules;
}
#NonNull
#Override
public RuleHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.item_recycler_rule, parent, false);
return new RuleHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RuleHolder holder, int position) {
Rule rule = rules.get(position);
holder.bind(rule);
}
#Override
public int getItemCount() {
return rules.size();
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
}
}
public class RuleLab {
private static RuleLab ruleLab;
private Context context;
private SQLiteDatabase database;
public static RuleLab get(Context context) {
if (ruleLab == null) {
ruleLab = new RuleLab(context);
}
return ruleLab;
}
private RuleLab (Context context) {
context = context.getApplicationContext();
database = new RuleBaseHelper(context).getWritableDatabase();
}
public List<Rule> getRules() {
List<Rule> rules = new ArrayList<>();
RuleCursorWrapper cursor = queryRules(null, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
rules.add(cursor.getRule());
cursor.moveToNext();
}
} finally {
cursor.close();
}
return rules;
}
public Rule getRule(int id) {
RuleCursorWrapper cursor = queryRules("_id = ?", new String[] {Integer.toString(id)});
try {
if (cursor.getCount() == 0) {
return null;
}
cursor.moveToFirst();
return cursor.getRule();
} finally {
cursor.close();
}
}
private static ContentValues getContentValues(Rule rule) {
ContentValues values = new ContentValues();
values.put("elect", rule.isElect() ? 1 : 0);
return values;
}
public void updateRule (Rule rule) {
String idString = Integer.toString(rule.getId());
ContentValues values = getContentValues(rule);
database.update("rules", values,
"_id" + " = ?",
new String[] {idString});
}
private RuleCursorWrapper queryRules (String whereClause, String[] whereArgs) {
Cursor cursor = database.query(
"rules",
null,
whereClause,
whereArgs,
null,
null,
"elect DESC"
);
return new RuleCursorWrapper(cursor);
}
}

behavior explanation: Using LiveData to update adapter with DiffUtil

I am updating my recyclerview by using LiveData as below:
viewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
viewModel.getPurchaseList().observe(getViewLifecycleOwner(), new Observer<List<ProductsObject>>() {
#Override
public void onChanged(#Nullable List<ProductsObject> productsObjects) {
adapter.submitList(productsObjects);
//adapter.notifyDataSetChanged();
}
});
And I am using a FloatActionButton to change the value of my MutableLiveData as below:
FloatingActionButton fab = view.findViewById(R.id.cart_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewModel.setPurchasePrice(0, 101.2);
}
});
All the data gets changed and onChanged is called as expected, but it only updates my recyclerview when I enable the adapter.notifyDataSetChanged();
If I create a new ProductsObject inside the FAB and submit a new list, the recyclerview gets updated without calling adapter.notifyDataSetChanged(); as below:
FloatingActionButton fab = view.findViewById(R.id.cart_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//viewModel.setPurchaseAmount(0, 101.2);
ProductsObject prod = new ProductsObject("6666", 5, 152.2, "new product");
List<ProductsObject> prodList = new ArrayList<>();
prodList.add(prod);
adapter.submitList(prodList);
}
});
I appreciate if anyone could explain why.
Here is my adapter:
public class CartFragAdapter extends RecyclerView.Adapter<CartFragAdapter.CartFragViewHolder> {
private static final String TAG = "debinf PurchaseAdap";
private static final DiffUtil.ItemCallback<ProductsObject> DIFF_CALLBACK = new DiffUtil.ItemCallback<ProductsObject>() {
#Override
public boolean areItemsTheSame(#NonNull ProductsObject oldProduct, #NonNull ProductsObject newProduct) {
Log.i(TAG, "areItemsTheSame: old is "+oldProduct.getCode()+" ; new is "+newProduct.getCode());
return oldProduct.getCode().equals(newProduct.getCode());
}
#Override
public boolean areContentsTheSame(#NonNull ProductsObject oldProduct, #NonNull ProductsObject newProduct) {
Log.i(TAG, "areContentsTheSame: old is "+oldProduct.getPrice()+" ; new is "+newProduct.getPrice());
return oldProduct.getPrice() == newProduct.getPrice();
}
};
private AsyncListDiffer<ProductsObject> differ = new AsyncListDiffer<ProductsObject>(this, DIFF_CALLBACK);
#NonNull
#Override
public CartFragViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_purchase, parent, false);
return new CartFragViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CartFragViewHolder holder, int position) {
final ProductsObject purchaseList = differ.getCurrentList().get(position);
holder.mCode.setText(purchaseList.getCode());
holder.mPrice.setText(String.valueOf(purchaseList.getPrice()));
holder.mDescription.setText(purchaseList.getDescription());
}
#Override
public int getItemCount() {
Log.i(TAG, "getItemCount");
return differ.getCurrentList().size();
}
public void submitList(List<ProductsObject> products){
Log.i(TAG, "submitList: products.size is "+products.size());
differ.submitList(products);
}
public class CartFragViewHolder extends RecyclerView.ViewHolder {
public TextView mCode, mPrice, mDescription;
public CartFragViewHolder(#NonNull View itemView) {
super(itemView);
mCode = (TextView) itemView.findViewById(R.id.item_productCode);
mPrice = (TextView) itemView.findViewById(R.id.item_productPrice);
mDescription = (TextView) itemView.findViewById(R.id.item_productDescription);
}
}
}
And here is my ViewModel:
public class MyViewModel extends ViewModel {
MutableLiveData<List<ProductsObject>> purchaseList = new MutableLiveData<>();
public LiveData<List<ProductsObject>> getPurchaseList() {
return purchaseList;
}
public void setPurchasePrice(int position, double price) {
List<ProductsObject> itemList = purchaseList.getValue();
if (itemList != null && itemList.get(position) != null) {
Log.i("debinf ViewModel", "setPurchaseAmount: "+itemList.get(position).getPrice());
itemList.get(position).setPrice(price);
purchaseList.postValue(itemList);
}
}
}
AsyncListDiffer saves only the reference of the list. This means that if you submit a modified list instead of submitting a new list, AsncListDiffer won't be able to detect any difference because both the previous list and the new list are referencing the same list with the same items.
To fix this you need to create a new list and new item. Change MyViewModel#setPurchasePrice as below:
public void setPurchasePrice(int position, double price) {
List<ProductsObject> itemList = purchaseList.getValue();
if (itemList != null && itemList.get(position) != null) {
List<ProductsObject> newList = new ArrayList<>();
for (int i = 0; i < itemList.size(); i++) {
ProductsObject prevProd = itemList.get(i);
if (i != position) {
newList.add(prevProd);
} else {
ProductsObject newProd = new ProductsObject(..., price, ...);
newList.add(newProd);
}
}
purchaseList.postValue(newList);
}
}

How do i update my firebase adapter with new items without repopulating the entire list

I'm trying to implement endless scrolling in my firebase recycler view.I limit my query to 5 items then the users scrolls to the end of the list the query is updated and the limit is increased my another 5. But the adapter only updates when i leave and return to the activity. I tried notifydatasetchange(), but that doesn't work. I tried recyclerview.setadapter(). It works but it also resets the scroll position of my recycler view.Nothing else seems to work.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view=inflater.inflate(R.layout.card_view,container,false);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseUpvote= FirebaseDatabase.getInstance().getReference().child("Upvote");
mAuth=FirebaseAuth.getInstance();
recyclerView = (RecyclerView) view.findViewById(R.id.recycleview_new);
recyclerView.setHasFixedSize(true);
mLayoutManager=(new LinearLayoutManager(getActivity()));
recyclerView.setLayoutManager(mLayoutManager);
mDatabaseUpvote.keepSynced(true);
mDatabase.keepSynced(true);
query=mDatabase.limitToFirst(count);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
firstItem=mLayoutManager.findLastVisibleItemPosition();
ItemCount=recyclerView.getChildCount();
TotalItemCount=mLayoutManager.getItemCount();
if (loading){
if (TotalItemCount>prevTotal){
loading=false;
prevTotal=TotalItemCount;
}
}
if (!loading && (TotalItemCount-firstItem) <= (firstItem+visthresh)){
count=count+2;
query=mDatabase.limitToFirst(count);
Toast.makeText(getActivity(), "ThresholdReached", Toast.LENGTH_SHORT).show();
loading=true;
}
}
});
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cards, Postviewholder>(
Cards.class,
R.layout.cards,
Postviewholder.class,
query
) {
#Override
protected void populateViewHolder(final Postviewholder viewHolder, Cards model, final int position) {
final String postKey=getRef(position).getKey();
viewHolder.setUsername(model.getUsername());
viewHolder.setImage(getActivity(),model.getImage());
viewHolder.setimage_icon(getActivity(),model.getImageicon());
viewHolder.setTitle(model.getTitle());
viewHolder.setTextColor(model.getTextColor());
viewHolder.setUpvote(postKey);
viewHolder.post_Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2= new Intent(getActivity(),View_post.class);
intent2.putExtra("Userprofile",postKey);
startActivity(intent2);
}
});
viewHolder.imageicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2= new Intent(getActivity(),UserActivity_2.class);
intent2.putExtra("Userprofile",postKey);
startActivity(intent2);
}
});
viewHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProcessUpvote = true;
mDatabaseUpvote.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (ProcessUpvote) {
if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseUpvote.child(postKey).child(mAuth.getCurrentUser().getUid()).removeValue();
ProcessUpvote = false;
} else {
mDatabaseUpvote.child(postKey).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
ProcessUpvote = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
if (sharedPreferences != null) {
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(getActivity());
Posit=(preferences.getInt(RV_POS_INDEX,0));
mRvTopView=(preferences.getInt(RV_TOP_VIEW,0));
Toast.makeText(getActivity(), "RestoreState", Toast.LENGTH_SHORT).show();
firebaseRecyclerAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
public void onItemRangeInserted(int positionStart, int itemCount) {
mLayoutManager.scrollToPositionWithOffset(Posit, mRvTopView);
}
});
}
return view;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Posit = mLayoutManager.findFirstVisibleItemPosition();
View startView = recyclerView.getChildAt(0);
mRvTopView = (startView == null) ? 0 : (startView.getTop() - recyclerView.getPaddingTop());
Toast.makeText(getActivity(), "SaveState", Toast.LENGTH_SHORT).show();
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt(RV_POS_INDEX,Posit);
editor.putInt(RV_TOP_VIEW,mRvTopView);
editor.apply();
}
public static class Postviewholder extends RecyclerView.ViewHolder {
View mView;
ImageView upvote;
ImageView imageicon;
ImageView post_Image;
private DatabaseReference mDatabaseUpvote;
private FirebaseAuth mAuth;
public Postviewholder(View itemView) {
super(itemView);
mView = itemView;
imageicon = (ImageView) mView.findViewById(R.id.Post_imiageicon);
post_Image = (ImageView) mView.findViewById(R.id.CardImage);
upvote = (ImageView) mView.findViewById(R.id.upvote);
mDatabaseUpvote = FirebaseDatabase.getInstance().getReference().child("Upvote");
mAuth = FirebaseAuth.getInstance();
}
public void setUpvote(final String postKey) {
mDatabaseUpvote.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {
upvote.setImageResource(R.drawable.ic_thumb_up_black_24dp2);
} else {
upvote.setImageResource(R.drawable.ic_thumb_up_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setImage(final Context ctx, final String image) {
final ImageView imageView = (ImageView) mView.findViewById(R.id.CardImage);
Glide.with(ctx)
.load(image)
.into(imageView);
}
public void setTitle(String title) {
TextView cardtitle = (TextView) mView.findViewById(R.id.cardTitle);
cardtitle.setText(title);
}
public void setUsername(String username) {
TextView post_username = (TextView) mView.findViewById(R.id.post_username);
post_username.setText(username);
}
public void setimage_icon(final Context ctx, final String imageicon) {
final ImageView image_icon = (ImageView) mView.findViewById(R.id.Post_imiageicon);
Glide.with(ctx)
.load(imageicon)
.into(image_icon);
}
public void setTextColor(int TextColor) {
CardView cardView= (CardView)mView.findViewById(R.id.Cardview_card);
TextView post_username = (TextView) mView.findViewById(R.id.post_username);
TextView cardtitle = (TextView) mView.findViewById(R.id.cardTitle);
int textcolr=getContrastColor(TextColor);
int white=Color.WHITE;
int resultColor = blendARGB(TextColor,white,0.1f);
cardView.setCardBackgroundColor(resultColor);
cardtitle.setTextColor(textcolr);
post_username.setTextColor(textcolr);
}
}
}

Resources