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'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);
}
}
}
I need to delete the item from database and ListView. I can delete the item from ListView but i can't delete it from database. I think the problem is in getting the position of the item from the database i tried to do it in my own but it does not work. I don't know what should I do.Help me to slove this.
myDB = new DbHandler(this);
userList = new ArrayList<>();
data = myDB.getListContents();
numRows = data.getCount();
if (numRows == 0) {
Toast.makeText(AddCount.this, "No Items", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
user = new User(data.getString(1), data.getString(2));
userList.add(user);
}
}
adapter = new Two_columnListAdapter(this, R.layout.list_item_layout, userList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, final int arg2, final long arg3) {
final AlertDialog.Builder delete = new AlertDialog.Builder(AddCount.this);
delete.setIcon(R.drawable.ic_baseline_delete_24);
delete.setTitle("Are you sure");
delete.setMessage("Do you want to delete this item?");
delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
DbHandler db = new DbHandler(getApplicationContext());
myDB.deleteData(userList.get(arg2));
userList.remove(arg2);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Deleted" ,Toast.LENGTH_SHORT).show();
}
});`
`Two_columnAdapter.java
public class Two_columnListAdapter extends ArrayAdapter<User> {
private LayoutInflater layoutInflater;
private ArrayList<User>users;
private int mviewResourceId;
public Two_columnListAdapter(Context context,int textViewResourceId,ArrayList<User>users){
super(context,textViewResourceId,users);
this.users = users;
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mviewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = layoutInflater.inflate(mviewResourceId,null);
User user= users.get(position);
if (user != null){
TextView text = (TextView)convertView.findViewById(R.id.title);
TextView num = (TextView)convertView.findViewById(R.id.value);
if (text != null){
text.setText(user.getText());
}
if (num != null){
num.setText(user.getNum());
}
}
return convertView;
}
DatabaseHelpher(delete the single row from database)
public void deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Inputs, KEY_ID + " =?", new String[]{id});
db.close();
}
You can save the return data inside a model class instead of a list. Then call the setOnLongClickListener in your adapter class, inside onBindViewHolder.
class listHolder extends RecyclerView.ViewHolder{
private View view;
public listHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
}
}
#Override
public void onBindViewHolder(#NonNull listHolder listHolder, int position, #NonNull userModel userModel) {
viewHolder.view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do somethings....
}
});
For more info you can check out this link, Hope this helps!
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);
}
}
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);
}
}
}