Migrate my normal RecyclerView to RecyclerView Databinding - java

I have issue when I change some value, example delete comment in my recyclerview it's doesn't update automatically, Google says use LiveData DataBinding RecyclerView, is anyone ever to make RecyclerView LiveData databinding please help me out
This is my MainActivity.java
public class TabDetailHotActivity extends AppCompatActivity {
//GLOBAL
public static MainActivity mainActivity_;
TextView TVGameDate;
TextView TVGameTitle;
ImageView IMGGameImage;
TextView TVSeenCounter;
TextView TVCommentCounter;
TextView TVLikeCounter;
ImageView IMGSeenView;
ImageView IMGCommentView;
ImageView IMGLikeView;
ImageView ICONHotTrendingNewsSaving;
//EVENT BUS
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredMessageTrending event) {
getMessageTrendingMainActivity(event.SendMessageUrutan, event.SendTotalThread, event.SendMessageIDComment, event.SendMessageComment, event.SendMessageEntryTime, event.SendMessageisEdited, event.SendMessageEditTime);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredMessageTrendingLogin event) {
getMessageTrendingLoginMainActivity(event.SendMessageUrutan, event.SendTotalThread, event.SendMessageIDComment, event.SendMessageComment, event.SendMessageEntryTime, event.SendMessageisEdited, event.SendMessageEditTime, event.SendMessageEditable);
}
public void getMessageTrendingMainActivity(int ReceivedMessageUrutan, int ReceivedTotalThread, String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime){
Toast.makeText(this, "Load Comment Not Login :( >> ReceivedMessageComment:"+ReceivedMessageComment+", Toast.LENGTH_LONG).show();
}
public void getMessageTrendingLoginMainActivity(int ReceivedMessageUrutan, int ReceivedTotalThread, String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime, int ReceivedMessageEditable){
Toast.makeText(this, "Load Comment Login :) >> ReceivedMessageComment:" + ReceivedMessageComment, Toast.LENGTH_LONG).show();
createDummyDataComment(ReceivedMessageUrutan, ReceivedTotalThread, ReceivedMessageIDComment, ReceivedMessageComment, ReceivedMessageEntryTime, ReceivedMessageEdited, ReceivedMessageEditTime, ReceivedMessageEditable);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitydetail_tabhot);
ToolbarX = findViewById(R.id.toolbar);
setSupportActionBar(ToolbarX);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle("");
Intent intent = getIntent();
mDummyIDContent = intent.getStringExtra("DummyIDContentPKG");
mDummyTitle = intent.getStringExtra("DummyTitlePKG");
mDummyPublishTime = intent.getStringExtra("DummyPublishTimePKG");
mDummyImageOriPKG = intent.getStringExtra("DummyImageOriPKG");
mDummyShortDescription = intent.getStringExtra("DummyShortDescriptionPKG");
mDummySeen = intent.getIntExtra("DummySeenPKG", 0);
mDummyComment = intent.getIntExtra("DummyCommentPKG", 0);
mDummyLike = intent.getIntExtra("DummyLikePKG", 0);
mDummyisComment = intent.getIntExtra("DummyisCommentPKG", 0);
mDummyisLike = intent.getIntExtra("DummyisLikePKG", 0);
mDummyisBookmark = intent.getIntExtra("DummyisBookmarkPKG", 0);
date_Behaviour = findViewById(R.id.date_behavior);
IMGGameImage = findViewById(R.id.backdrop);
TVGameDate = findViewById(R.id.date);
TVGameTitle = findViewById(R.id.title);
TVSeenCounter = findViewById(R.id.TV_SeenCounter);
TVCommentCounter = findViewById(R.id.TV_CommentCounter);
TVLikeCounter = findViewById(R.id.TV_LikeCounter);
RequestOptions requestOptions = new RequestOptions();
requestOptions.error(UtilsNews.getRandomDrawbleColor());
TVGameDate.setText(mDummyPublishTime);
TVGameTitle.setText(mDummyTitle);
TVSeenCounter.setText(String.valueOf(mDummySeen));
TVCommentCounter.setText(String.valueOf(mDummyComment));
TVLikeCounter.setText(String.valueOf(mDummyLike));
Glide.with(this)
.load(mDummyImageOriPKG)
.apply(requestOptions)
.transition(DrawableTransitionOptions.withCrossFade())
.into(IMGGameImage);
/* initWebView(mUrl);*/
ImageButton BTNSendMessageDetailHotTrendingNews = findViewById(R.id.BTN_SendMessageDetailHotTrendingNews);
final TextView ETSendMessageDetailHotTrendingNews = findViewById(R.id.ET_SendMessageDetailHotTrendingNews);
BTNSendMessageDetailHotTrendingNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String TheMessage = ETSendMessageDetailHotTrendingNews.getText().toString();
if(!TheMessage.equals("")){
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("SendComment", mDummyIDContent, TheMessage);
}
}else{
Toast.makeText(TabDetailHotActivity.this, "You don't send anything", Toast.LENGTH_SHORT).show();
}
ETSendMessageDetailHotTrendingNews.setText("");
}
});
//
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("LoadComment", mDummyIDContent, "");
}
}
private void initWebView(String url) {
WebView webView = findViewById(R.id.webView);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url);
}
ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments = new ArrayList<ModelDetailHotTrendingNewsComment>();
AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener listenerDetailHotTrendingNewsComment;
public void createDummyDataComment(int ReceivedMessageUrutan, int ReceivedTotalThread, final String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime, int ReceivedMessageEditable) {
modelDetailHotTrendingNewsComments.add(new ModelDetailHotTrendingNewsComment(ReceivedMessageIDComment,ReceivedMessageComment,ReceivedMessageEntryTime,ReceivedMessageEditable,ReceivedMessageEditTime));
if(ReceivedMessageUrutan == ReceivedTotalThread-1){
listenerDetailHotTrendingNewsComment = new AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener(){
#Override
public void onRowDetailHotTrendingNewsContainerClick(View view, int position) {
}
#Override
public void onRowMessageEditClick(View view, int position) {
}
#Override
public void onRowMessageDeleteClick(View view, final int position) {
String[] YOURCHOICE = {"Yes", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(TabDetailHotActivity.this);
builder.setTitle("Do you want to delete this comment?");
builder.setItems(YOURCHOICE, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Toast.makeText(TabDetailHotActivity.this, "Deleted Successfully!", Toast.LENGTH_SHORT).show();
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("DeleteComment", modelDetailHotTrendingNewsComments.get(position).getIdcontent(), "");
}
}else if(which == 1){
Toast.makeText(TabDetailHotActivity.this, "You don't delete the Comment", Toast.LENGTH_SHORT).show();
}
}
});
builder.show();
}
};
RecyclerView RVDetailHotTrendingNewsComment = findViewById(R.id.RVDetail_HotTrendingNewsComment);
RVDetailHotTrendingNewsComment.setHasFixedSize(true);
AdapterDetailHotTrendingNewsComment adapterDetailHotTrendingNewsComment = new AdapterDetailHotTrendingNewsComment(this, modelDetailHotTrendingNewsComments, listenerDetailHotTrendingNewsComment);
RVDetailHotTrendingNewsComment.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
RVDetailHotTrendingNewsComment.setAdapter(adapterDetailHotTrendingNewsComment);
//Optimized
RVDetailHotTrendingNewsComment.setHasFixedSize(true);
RVDetailHotTrendingNewsComment.setItemViewCacheSize(20);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
supportFinishAfterTransition();
}
//EVENTBUS
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
}
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#color/darkgrey"
tools:context=".TabDetailHotActivity">
<androidx.core.widget.NestedScrollView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:background="#color/darkgrey"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:background="#color/darkgrey"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:textColor="#color/colorWhite"
android:textStyle="bold"
android:fontFamily="sans-serif-light"
android:textSize="19sp"
android:text="Title of News"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_below="#id/title"
android:textColor="#color/colorWhite"
android:layout_marginTop="10dp"
android:maxLines="1"
android:drawablePadding="10dp"
android:singleLine="true"
android:ellipsize="end"
android:text="a time ago" />
<ImageView
android:id="#+id/IMG_SeenView"
android:src="#drawable/watch"
android:layout_marginLeft="8dp"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/TV_SeenCounter"
android:paddingTop="2dp"
android:layout_marginTop="1dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_SeenCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/IMG_CommentView"
android:text="999"
android:layout_marginTop="2dp"
android:textSize="14dp"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
<ImageView
android:id="#+id/IMG_CommentView"
android:src="#drawable/comment_off"
android:layout_toLeftOf="#id/TV_CommentCounter"
android:layout_alignParentBottom="true"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_CommentCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/IMG_LikeView"
android:layout_marginTop="2dp"
android:text="999"
android:textSize="14dp"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
<ImageView
android:id="#+id/IMG_LikeView"
android:src="#drawable/heart_off"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/TV_LikeCounter"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_LikeCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:layout_alignParentEnd="true"
android:text="999"
android:textSize="14dp"
android:layout_alignParentBottom="true"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/darkgrey">
<ProgressBar
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/progress_bar"
android:layout_marginTop="50dp"
android:layout_marginBottom="70dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/RL_Bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#FFFFFF"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/ET_SendMessageDetailHotTrendingNews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:hint="Type a comment..."
android:layout_toLeftOf="#id/BTN_SendMessageDetailHotTrendingNews"
android:layout_centerVertical="true"/>
<ImageButton
android:id="#+id/BTN_SendMessageDetailHotTrendingNews"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/ic_send_black_24dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/darkgrey">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/RVDetail_HotTrendingNewsComment"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<FrameLayout
android:id="#+id/date_behavior"
app:layout_anchor="#+id/appbar"
app:behavior_autoHide="true"
android:adjustViewBounds="true"
app:layout_anchorGravity="right|end|bottom"
android:clickable="false"
android:background="#drawable/round_white"
android:layout_width="wrap_content"
android:padding="5dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="410dp"
android:layout_height="wrap_content"
tools:ignore="UnusedAttribute">
<ImageView
android:src="#drawable/ic_date"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<TextView
android:textColor="#606060"
android:id="#+id/date"
android:layout_marginLeft="27dp"
android:layout_marginRight="10dp"
android:text="01 January 1990"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
This is AdapterComment.java
public class AdapterDetailHotTrendingNewsComment extends RecyclerView.Adapter {
private Context mContext;
private ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments;
private AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener;
public AdapterDetailHotTrendingNewsComment(Context mContext, ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments, AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener) {
this.mContext = mContext;
this.modelDetailHotTrendingNewsComments = modelDetailHotTrendingNewsComments;
this.mListener = mListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemdetail_hottrendingnewscomment, null);
return new DetailHotTrendingNewsViewHolder(v, mListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final DetailHotTrendingNewsViewHolder detailHotTrendingNewsViewHolder = (DetailHotTrendingNewsViewHolder) holder;
final ModelDetailHotTrendingNewsComment modelDetailHotTrendingNewsCommentX = modelDetailHotTrendingNewsComments.get(position);
Glide.with(mContext).load(modelDetailHotTrendingNewsCommentX.getMessageimage()).into(detailHotTrendingNewsViewHolder.IMGMessageImage);
detailHotTrendingNewsViewHolder.TVMessageUsername.setText(modelDetailHotTrendingNewsCommentX.getMessageusername());
detailHotTrendingNewsViewHolder.TVMessageDescription.setText(modelDetailHotTrendingNewsCommentX.getMessagedescription());
detailHotTrendingNewsViewHolder.TVMessageDate.setText(modelDetailHotTrendingNewsCommentX.getMessagedate());
}
#Override
public int getItemCount() {
int itemCount = modelDetailHotTrendingNewsComments.size();
return itemCount;
}
public class DetailHotTrendingNewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView IMGMessageImage;
TextView TVMessageUsername;
TextView TVMessageDescription;
TextView TVMessageDate;
private RelativeLayout ROWDetailHotTrendingNewsContainer;
TextView TVMessageEdit;
ImageView IMGMessageDelete;
private AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener;
public DetailHotTrendingNewsViewHolder(View itemView, AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener listener) {
super(itemView);
IMGMessageImage = itemView.findViewById(R.id.IMG_MessageImage);
TVMessageUsername = itemView.findViewById(R.id.TV_MessageUsername);
TVMessageDescription = itemView.findViewById(R.id.TV_MessageDescription);
TVMessageDate = itemView.findViewById(R.id.TV_MessageDate);
ROWDetailHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_DetailHotTrendingNewsContainer);
TVMessageEdit = itemView.findViewById(R.id.TV_MessageEdit);
IMGMessageDelete = itemView.findViewById(R.id.IMG_MessageDelete);
mListener = listener;
ROWDetailHotTrendingNewsContainer.setOnClickListener(this);
TVMessageEdit.setOnClickListener(this);
IMGMessageDelete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ROW_DetailHotTrendingNewsContainer:
mListener.onRowDetailHotTrendingNewsContainerClick(ROWDetailHotTrendingNewsContainer, getAdapterPosition());
break;
case R.id.TV_MessageEdit:
mListener.onRowMessageEditClick(TVMessageEdit, getAdapterPosition());
break;
case R.id.IMG_MessageDelete:
mListener.onRowMessageDeleteClick(IMGMessageDelete, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowDetailHotTrendingNewsContainerClick(View view, int position);
void onRowMessageEditClick(View view, int position);
void onRowMessageDeleteClick(View view, int position);
}
}
This is ModelComment.java
public class ModelDetailHotTrendingNewsComment {
private String idcontent;
private String messageimage;
private String messageusername;
private String messagedescription;
private String messagedate;
private int messageisedit;
private String messageedittime;
private String messageedit;
private String messagedelete;
public ModelDetailHotTrendingNewsComment(String idcontent, String messagedescription, String messagedate, int messageisedit, String messageedittime) {
this.idcontent = idcontent;
this.messagedescription = messagedescription;
this.messagedate = messagedate;
this.messageisedit = messageisedit;
this.messageedittime = messageedittime;
}
public String getIdcontent() {
return idcontent;
}
public void setIdcontent(String idcontent) {
this.idcontent = idcontent;
}
public String getMessageimage() {
return messageimage;
}
public void setMessageimage(String messageimage) {
this.messageimage = messageimage;
}
public String getMessageusername() {
return messageusername;
}
public void setMessageusername(String messageusername) {
this.messageusername = messageusername;
}
public String getMessagedescription() {
return messagedescription;
}
public void setMessagedescription(String messagedescription) {
this.messagedescription = messagedescription;
}
public String getMessagedate() {
return messagedate;
}
public void setMessagedate(String messagedate) {
this.messagedate = messagedate;
}
public String getMessageedittime() {
return messageedittime;
}
public void setMessageedittime(String messageedittime) {
this.messageedittime = messageedittime;
}
public String getMessageedit() {
return messageedit;
}
public void setMessageedit(String messageedit) {
this.messageedit = messageedit;
}
public String getMessagedelete() {
return messagedelete;
}
public void setMessagedelete(String messagedelete) {
this.messagedelete = messagedelete;
}
}

Related

onSwiped() or onMove() method not Working

I want to develop android application and I am new.
I don't get any response when I touch the screen, it doesn't even move.
I can't perform any drag operations
Can you help me?
here are my codes
CartAdapter.java
public class CartAdapter extends RecyclerView.Adapter<CartViewHolder> {
private List<Order> listData = new ArrayList<>();
private Cart cart;
public CartAdapter(List<Order> listData,Cart cart) {
this.listData = listData;
this.cart = cart;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(cart);
View itemView = inflater.inflate(R.layout.cart_layout,parent,false);//inflate kontrol...
return new CartViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder holder, int position) {
Picasso.with(cart)
.load(listData.get(position).getImage())
.resize(70,70)
.centerCrop()
.into(holder.cart_image);
holder.btn_quantity.setNumber(listData.get(position).getQuantity());
holder.btn_quantity.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {
#Override
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
Order order = listData.get(position);
order.setQuantity(String.valueOf(newValue));
new Database(cart).updateCart(order);
int total = 0;
List<Order> orders = new Database(cart).getCarts(Common.currentUser.getPhone());
for (Order item : orders)
total += (Float.parseFloat(order.getPrice())) * (Float.parseFloat(item.getQuantity()));
//en US
Locale locale = new Locale("tr", "TR");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
cart.textTotalPrice.setText(fmt.format(total));
}
});
Locale locale = new Locale("tr", "TR");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);//Hata Cıkarsa Tekar Bak...
float price = (Float.parseFloat(listData.get(position).getPrice()))*(Float.parseFloat(listData.get(position).getQuantity()));
holder.txt_price.setText(fmt.format(price));
holder.txt_cart_name.setText(listData.get(position).getProductName());
}
#Override
public int getItemCount() {
return listData.size();
}
public Order getItem(int position){
return listData.get(position);
}
public void removeItem(int position)
{
listData.remove(position);
notifyItemRemoved(position);
}
public void restoreItem(Order item,int position)
{
listData.add(position,item);
notifyItemInserted(position);
}
}`
CartViewHolder.java
public class CartViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
, View.OnCreateContextMenuListener{
public TextView txt_cart_name,txt_price;
public ImageView cart_image;
public ElegantNumberButton btn_quantity;
public ConstraintLayout view_background;
public ConstraintLayout view_foreground;
private ItemClickListener itemClickListener;
public void setTxt_cart_name(TextView txt_cart_name) {
this.txt_cart_name = txt_cart_name;
}
public CartViewHolder(View itemView){
super(itemView);
txt_cart_name = itemView.findViewById(R.id.cart_item_name);
txt_price = itemView.findViewById(R.id.cart_item_Price);
btn_quantity = (ElegantNumberButton)itemView.findViewById(R.id.btn_quantity);
cart_image = itemView.findViewById(R.id.cart_image);
view_background = (ConstraintLayout) itemView.findViewById(R.id.view_background);
view_foreground= (ConstraintLayout) itemView.findViewById(R.id.view_foreground);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View view) {
}
#Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
contextMenu.setHeaderTitle("İŞLEMİ SEÇİNİZ");
contextMenu.add(0,0,getAdapterPosition(), Common.DELETE);
}
}
RecyclerItemTouchHelper.java
public class RecyclerItemTouchHelper extends ItemTouchHelper.SimpleCallback {
private RecyclerItemTouchHelperListener listener;
public RecyclerItemTouchHelper(int dragDirs, int swipeDirs, RecyclerItemTouchHelperListener listener) {
super(dragDirs, swipeDirs);
this.listener = listener;
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
if (listener != null)
listener.onSwiped(viewHolder,direction,viewHolder.getAdapterPosition());
}
#Override
public int convertToAbsoluteDirection(int flags, int layoutDirection) {
return super.convertToAbsoluteDirection(flags, layoutDirection);
}
#Override
public void clearView(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder) {
View foregroundView = ((CartViewHolder)viewHolder).view_foreground;
getDefaultUIUtil().clearView(foregroundView);
}
#Override
public void onChildDraw(#NonNull Canvas c, #NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
View foregroundView = ((CartViewHolder) viewHolder).view_foreground;
getDefaultUIUtil().onDraw(c, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive);
}
#Override
public void onSelectedChanged(#Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
if (viewHolder != null){
View foregroundView = ((CartViewHolder)viewHolder).view_foreground;
getDefaultUIUtil().onSelected(foregroundView);
}
}
#Override
public void onChildDrawOver(#NonNull Canvas c, #NonNull RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
View foregroundView = ((CartViewHolder)viewHolder).view_foreground;
getDefaultUIUtil().onDrawOver(c,recyclerView,foregroundView,dX,dY,actionState,isCurrentlyActive);
}
}
RecyclerItemTouchHelperLister
public interface RecyclerItemTouchHelperListener {
void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position);
}
Cart.java
public class Cart extends AppCompatActivity implements RecyclerItemTouchHelperListener {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
public TextView textTotalPrice;
Button btnPlace;
List<Order> cart = new ArrayList<>();
CartAdapter adapter;
RelativeLayout rootLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
//Firebase
database = FirebaseDatabase.getInstance();
requests=database.getReference("Requests");
rootLayout = findViewById(R.id.rootLayout);
//Swipe to delete
ItemTouchHelper.SimpleCallback ItemTouchHelperCallback = new RecyclerItemTouchHelper(0,ItemTouchHelper.LEFT,this);
new ItemTouchHelper(ItemTouchHelperCallback).attachToRecyclerView(recyclerView);
//init
recyclerView = findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
textTotalPrice = findViewById(R.id.total);
btnPlace = findViewById(R.id.btnPlaceOrder);
btnPlace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cart.size() > 0)
showAlertDialog();
else
Toast.makeText(Cart.this, "Sipariş vermek için sepetine ürün eklemelisin", Toast.LENGTH_SHORT).show();
}
});
loadListFood();
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("One more step");
alertDialog.setMessage("Enter your address");
final EditText kmpsAddress = new EditText(Cart.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
kmpsAddress.setLayoutParams(lp);
alertDialog.setView(kmpsAddress);
alertDialog.setIcon(R.drawable.cart_market);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
kmpsAddress.getText().toString(),
textTotalPrice.getText().toString(),
"0",
cart
);
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
new Database(Cart.this).cleanCart(Common.currentUser.getPhone());
Toast.makeText(Cart.this, "Thank you, order place", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
}
private void loadListFood() {
cart = new Database(getBaseContext()).getCarts(Common.currentUser.getPhone());
adapter = new CartAdapter(cart,this);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
//Total Ücretin Hesaplanması
int total = 0;
for (Order order:cart)
total+=(Float.parseFloat(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
Locale locale = new Locale("tr","TR");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
textTotalPrice.setText(fmt.format(total));
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
if (item.getTitle().equals(Common.DELETE))
deleteCart(item.getOrder());
return true;
}
private void deleteCart(int position) {
cart.remove(position);
new Database(this).cleanCart(Common.currentUser.getPhone());
for (Order item:cart)
new Database(this).addToCart(item);
loadListFood();
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
if (viewHolder instanceof CartViewHolder)
{
String name = ((CartAdapter)recyclerView.getAdapter()).getItem(viewHolder.getAdapterPosition()).getProductName();
Order deleteItem = ((CartAdapter) recyclerView.getAdapter()).getItem(viewHolder.getAdapterPosition());
int deleteIndex = viewHolder.getAdapterPosition();
adapter.removeItem(deleteIndex);
new Database(getBaseContext()).removeFromCart(deleteItem.getProductId(),Common.currentUser.getPhone());
int total = 0;
List<Order> orders = new Database(getBaseContext()).getCarts(Common.currentUser.getPhone());
for (Order item : orders)
total += (Float.parseFloat(item.getPrice())) * (Float.parseFloat(item.getQuantity()));
Locale locale = new Locale("tr", "TR");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
textTotalPrice.setText(fmt.format(total));
//Make snackbar
//snackbar
Snackbar snackbar = Snackbar.make(rootLayout,name + " ürün sepetten kaldırıldı!", Snackbar.LENGTH_LONG);
snackbar.setAction("GERİ AL", new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.restoreItem(deleteItem,deleteIndex);
new Database(getBaseContext()).addToCart(deleteItem);
//update txttotal
//calculation total price
//****Fiyatın Değiştirildiği Kısım****//
float total = 0;
List<Order> orders = new Database(getBaseContext()).getCarts(Common.currentUser.getPhone());
for(Order item:orders)
total +=(Float.parseFloat(item.getPrice()))*(Integer.parseInt(item.getQuantity()));
Locale locale = new Locale("tr","TR");
java.text.NumberFormat fmt = java.text.NumberFormat.getCurrencyInstance(locale);
textTotalPrice.setText(fmt.format(total));
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.show();
}
}
}
cart.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/rootLayout"
android:background="#fff"
android:layout_height="match_parent"
tools:context=".Cart">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/topNavi"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
>
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:src="#drawable/ic_baseline_arrow_back"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginStart="30dp" />
<TextView
android:id="#+id/cart_of_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_gravity="right"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:text="Sepet Detayları"
android:fontFamily="#font/poppins_bold"
android:textSize="15sp"
android:textColor="#000"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/listCart"
android:layout_width="match_parent"
app:layout_constraintTop_toBottomOf="#+id/topNavi"
android:layout_marginTop="20dp"
android:clipToPadding="false"
android:overScrollMode="never"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_height="wrap_content"
/>
<androidx.cardview.widget.CardView
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_alignParentBottom="true"
app:cardBackgroundColor="#F2CA7E"
android:layout_width="match_parent"
android:layout_height="100dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_margin="8dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:text="Toplam: "
android:textColor="#color/white"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/total"
android:text="10"
android:textColor="#color/white"
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<Button
android:id="#+id/btnPlaceOrder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Sepete Ekle"
android:layout_alignParentBottom="true"
android:textColor="#color/white"
android:layout_margin="8dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
cart_layout
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="0dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
app:cardUseCompatPadding="true"
app:cardCornerRadius="0dp">
<!-- cart_image,cart_item_name,cart_item_Price,btn_quantity-->
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/view_background"
android:background="#drawable/cart_item_bg_bg"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/cry_delete_astronaut"
android:layout_width="100dp"
android:layout_height="100dp"
app:lottie_rawRes="#raw/delete_cry_astronout"
app:lottie_autoPlay="true"
app:lottie_loop="true"
android:layout_marginEnd="10dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<TextView
android:id="#+id/delete_item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toStartOf="#+id/cry_delete_astronaut"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:text="Sepetten Kaldır"
android:textColor="#fff"
android:textSize="13sp"
android:fontFamily="#font/poppins_bold"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/view_foreground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/cart_item_bg">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/cart_image"
android:layout_width="104dp"
android:layout_height="87dp"
android:layout_gravity="center_vertical"
android:layout_marginStart="15dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/cart_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dominos Pizza"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:textColor="#000"
android:textSize="13sp"
android:fontFamily="#font/poppins_medium"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/cart_item_Price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="85"
android:textSize="15dp"
android:layout_marginStart="10dp"
android:fontFamily="#font/poppins_bold"
android:textColor="#00A082"
android:layout_marginBottom="10dp"
/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right">
<com.cepheuen.elegantnumberbutton.view.ElegantNumberButton
android:id="#+id/btn_quantity"
android:layout_width="92dp"
android:layout_height="38dp"
app:backGroundColor="#00A082"
app:layout_constraintStart_toStartOf="parent"
app:initialNumber="1"
app:layout_constraintEnd_toEndOf="parent"
app:textColor="#fff"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:textSize="5sp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

How to refer FIrebase Child in Child record in Firebase Recycler adapter to show in recyclerview

I have written code to list contacts in recycler view. But it doesn't display value in recycler view. The code is given below.
HomeActivity.java
private DatabaseReference mDatabase;
private RecyclerView PList;
private FirebaseRecyclerAdapter<project, ProjViewHolder> FBRA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
PList = findViewById(R.id.ProjList);
PList.setHasFixedSize(true);
PList.setLayoutManager(new LinearLayoutManager(this));
mDatabase = FirebaseDatabase.getInstance().getReference().child("Contacts");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<project> options = new FirebaseRecyclerOptions.Builder<project>().setQuery(mDatabase, project.class).build();
FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProjViewHolder holder, int position, #NonNull project model) {
String proj_key = getRef(position).getKey();
holder.cpname.setText(model.getCname());
holder.cplocation.setText(model.getCcity());
holder.ccname.setText(model.getPcontact());
holder.ccdesig.setText(model.getPdesig());
}
#Override
public ProjViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
return new ProjViewHolder(view);
}
};
PList.setAdapter(FBRA);
FBRA.startListening();
}
public class ProjViewHolder extends RecyclerView.ViewHolder {
TextView cpname, cplocation, ccname, ccdesig;
ProjViewHolder(#NonNull View itemView) {
super(itemView);
cpname = itemView.findViewById(R.id.FCName);
cplocation = itemView.findViewById(R.id.FCLocation);
ccname = itemView.findViewById(R.id.FPName);
ccdesig = itemView.findViewById(R.id.FPDesig);
}
}
#Override
protected void onStop() {
super.onStop();
FBRA.stopListening();
}
FormActivity.java
public class FormActivity extends AppCompatActivity {
private EditText CName, PContact,PDesig, CCity;
private FirebaseDatabase mDatabase;
private Button Fbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
CName = findViewById(R.id.CompName);
PContact = findViewById(R.id.PContact);
PDesig = findViewById(R.id.PDesig);
CCity = findViewById(R.id.CCity);
mDatabase = FirebaseDatabase.getInstance();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
String dCName = CName.getText().toString().trim();
String dPContact = PContact.getText().toString().trim();
String dPDesig = PDesig.getText().toString().trim();
String dCCity = CCity.getText().toString().trim();
String name = CName.getText().toString().trim();
DatabaseReference mDbRef = mDatabase.getReference().child("Contacts").child(name).push();
mDbRef.child("cname").setValue(dCName);
mDbRef.child("pcontact").setValue(dPContact);
mDbRef.child("pdesig").setValue(dPDesig);
mDbRef.child("ccity").setValue(dCCity);
Toast.makeText(FormActivity.this, "Contact Submitted Successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(FormActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
return super.onOptionsItemSelected(item);
}
}
Project.class
public class project {
String cname, pcontact, pdesig, ccity;
public project(){
}
public project(String cname, String pcontact, String pdesig, String ccity) {
this.cname = cname;
this.pcontact = pcontact;
this.pdesig = pdesig;
this.ccity = ccity;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getPcontact() {
return pcontact;
}
public void setPcontact(String pcontact) {
this.pcontact = pcontact;
}
public String getPdesig() {
return pdesig;
}
public void setPdesig(String pdesig) {
this.pdesig = pdesig;
}
public String getCcity() {
return ccity;
}
public void setCcity(String ccity) {
this.ccity = ccity;
}
}
HomeActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".HomeActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:id="#+id/ProjList"
/>
</RelativeLayout>
ProjRow.xml
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/FCName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:elegantTextHeight="true"
android:textColor="#color/colorBlue"
android:maxLength="25"
android:paddingTop="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="16dp"
android:textStyle="bold"
android:layout_marginTop="10dp"
/>
<TextView
android:id="#+id/FCLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:textAllCaps="true"
android:elegantTextHeight="true"
android:textColor="#color/colorDark"
android:layout_marginTop="13dp"
android:paddingTop="5dp"
android:textSize="14dp"
/>
<TextView
android:id="#+id/FPName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/FCName"
android:layout_alignParentLeft="true"
android:elegantTextHeight="true"
android:textStyle="bold"
android:textColor="#color/colorText"
android:paddingTop="5dp"
android:paddingRight="3dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textSize="15dp"
/>
<TextView
android:id="#+id/FPDesig"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/FCName"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:padding="5dp"
android:textSize="14dp"
android:textColor="#color/colorNext"
android:elegantTextHeight="true"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
the code is working fine without error. But the intended value is not captured from database. If push() is removed from DatabaseReference mDbRef = mDatabase.getReference().child("Contacts").child(name).push(); , it works absolutely fine. but it overwrites on existing data while adding new data for the same 'name'. After adding push, the data are getting stored in sub child record. Please guide me how to refer and get back the data in recycleview adapter.
The each record stored under 'Contacts' before adding push()but overwrites when added a person for the same company.
After adding push() each record stored under company name with unique key.

Why is the dialog design inconsistent on the device?

I designed dialog and assigned it a file named XML layout with a set of elements and then created a function to show it from within fragment. It appeared on the emulator screen well but it did not appear the same on the device.
What are the appropriate adjustments to be shown on the device well?
// layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="260dp"
android:layout_height="260dp"
android:orientation="vertical"
android:background="#f71717">
<LinearLayout
android:id="#+id/l_layout"
android:paddingTop="10dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:ignore="ObsoleteLayoutParam">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="ExtraText">
<RadioGroup
android:id="#+id/radioSex"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="UselessParent">
<RadioButton
android:id="#+id/second2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:button="#null"
android:layoutDirection="rtl"
android:textAlignment="textStart"
android:layout_gravity="start"
android:textDirection="rtl"
android:drawablePadding="10dp"
android:drawableRight="#android:drawable/btn_radio"
android:text="رفض"
android:textColor="#ffffff"
android:textSize="20dp"
tools:ignore="HardcodedText,RtlHardcoded,SpUsage" />
<RadioButton
android:id="#+id/second"
android:checked="true"
android:layoutDirection="rtl"
android:textDirection="rtl"
android:textAlignment="textStart"
android:layout_gravity="start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawablePadding="10dp"
android:drawableRight="#android:drawable/btn_radio"
android:text="قبول"
android:textColor="#ffffff"
android:textSize="20dp"
tools:ignore="HardcodedText,RtlHardcoded,SpUsage" />
</RadioGroup>
/>
</LinearLayout>
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:text="وقت التسليم"
android:textSize="20dp"
tools:ignore="HardcodedText,SpUsage" />
<Spinner
android:id="#+id/tex"
android:layout_width="172dp"
android:paddingRight="40dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_title"
android:drawSelectorOnTop="true"
android:popupBackground="#fff78c"
style="#style/spinner_style"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry,SpUsage"
android:entries="#array/day_"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/rl"
android:layout_width="250dp"
android:layout_height="129dp"
android:layout_below="#+id/l_layout"
android:background="#f71717"
android:layout_marginTop="0dp"
tools:ignore="ObsoleteLayoutParam">
<TextView
android:id="#+id/tv_h"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toStartOf="#+id/spinner_minutes2"
android:paddingLeft="10dp"
android:text="ساعة"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<TextView
android:id="#+id/tv_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/spinner_minutes2"
android:layout_alignBottom="#+id/spinner_minutes2"
android:layout_alignStart="#+id/button_holder"
android:paddingLeft="10dp"
android:text="دق"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<TextView
android:id="#+id/tv_pam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/spinner_minutes"
android:layout_alignBottom="#+id/spinner_minutes"
android:layout_alignEnd="#+id/spinner_minutes3"
android:layout_marginEnd="12dp"
android:paddingLeft="30dp"
android:text="ص/م"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<Spinner
android:id="#+id/spinner_minutes"
android:layout_width="85dip"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
style="#style/spinner_style"
android:popupBackground="#fff78c"
android:layout_alignStart="#+id/spinner_minutes2"
android:entries="#array/hour_" />
<Spinner
android:id="#+id/spinner_minutes2"
android:layout_width="85dip"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_minutes"
android:layout_marginStart="16dp"
android:popupBackground="#fff78c"
style="#style/spinner_style"
android:layout_toEndOf="#+id/tv_m"
android:entries="#array/hour_" />
<Spinner
android:id="#+id/spinner_minutes3"
android:layout_width="85dip"
android:layout_height="wrap_content"
style="#style/spinner_style"
android:paddingRight="20dp"
android:entries="#array/apm"
android:popupBackground="#fff78c"
tools:ignore="RtlHardcoded,RtlSymmetry"
android:layout_alignBaseline="#+id/spinner_minutes2"
android:layout_alignBottom="#+id/spinner_minutes2"
android:layout_toEndOf="#+id/spinner_minutes" />
<TextView
android:id="#+id/text_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="gone" />
<LinearLayout
android:id="#+id/button_holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_minutes"
android:layout_centerHorizontal="true"
android:paddingTop="10dp"
android:layout_marginTop="20dip">
<Button
android:id="#+id/button_set"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginLeft="10dip"
android:text="الغاء"
tools:ignore="ButtonStyle,HardcodedText,RtlHardcoded" />
<Button
android:id="#+id/button_cancel"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginRight="10dip"
android:text="إرسال"
tools:ignore="ButtonOrder,ButtonStyle,HardcodedText,RtlHardcoded" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
//calss Fragment:
public class Page_6Fragment extends android.support.v4.app.Fragment implements AdapterView.OnItemSelectedListener {
TextView t1,t2,t3,t4;
Spinner spin ,spin2,spin3,spin4;
Dialog dialog;
RecyclerView recyclerView;
List<Customer> customers;
CustomerAdapter adapter;
View rootView;
String TAG = "MainActivity - ";
Context context;
API api;
Activity a;
public static Page_6Fragment newInstance() {
Page_6Fragment fragment = new Page_6Fragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_customer, container, false);
// View rootView = inflater.inflate(R.xml.pref, container, false);
// Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);
// startActivity(intent);
this.context = getActivity();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
customers = new ArrayList<>();
adapter = new CustomerAdapter(context, customers);
adapter.setLoadMoreListener(new CustomerAdapter.OnLoadMoreListener(){
#Override
public void onLoadMore() {
recyclerView.post(new Runnable() {
#Override
public void run() {
int index = customers.size() - 1;
loadMore(index);
}
});
//Calling loadMore function in Runnable to fix the
// java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
//recyclerView.addItemDecoration(new VerticalLineDecorator(2));
recyclerView.setAdapter(adapter);
api = ServiceGenerator.createService(API.class);
load(0);
return rootView;
}
private void load(int index){
Call<List<Customer>> call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>(){
#Override
public void onResponse(Call<List<Customer>> call, Response<List<Customer>> response){
// Toast.makeText(getActivity(), "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
// Log.i("TRUE_TRUE","Yes"+response.body().get(0).title);
if(response.isSuccessful()){
customers.addAll(response.body());
adapter.notifyDataChanged();
// Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
}else{
Log.e(TAG," Response Error "+String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<List<Customer>> call, Throwable t) {
Log.e(TAG," Response Error "+t.getMessage());
}
});
}
private void loadMore(int index){
//add loading progress view
customers.add(new Customer("load"));
adapter.notifyItemInserted(customers.size()-1);
Call<List<Customer>>call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>(){
#Override
public void onResponse(Call<List<Customer>> call, Response<List<Customer>>response) {
if(response.isSuccessful()){
// remove loading view .......
customers.remove(customers.size()-1);
List<Customer>result=response.body();
if(result.size()>0){
// add loaded data
customers.addAll(result);
}else{//result size 0 means there is no more data available at server
adapter.setMoreDataAvailable(false);
//telling adapter to stop calling load more as no more server data available
Toast.makeText(context,"No More Data Available",Toast.LENGTH_LONG).show();
}
adapter.notifyDataChanged();
}else{
Log.e(TAG," Load More Response Error "+String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<List<Customer>>call,Throwable t) {
Log.e(TAG," Load More Response Error "+t.getMessage());
}
});
}
public void showDialog(Context context){
dialog = new Dialog(context);
dialog.setCancelable(true);
dialog.setContentView(R.layout.layout);
dialog.show();
String[] bankNames = {
"BO","SB","HD","PN","Bj"
};
t1= (TextView)dialog.findViewById(R.id.tv_h);
t2= (TextView)dialog.findViewById(R.id.tv_m);
t3= (TextView)dialog.findViewById(R.id.tv_title);
t4= (TextView)dialog.findViewById(R.id.tv_pam);
spin =(Spinner)dialog.findViewById(R.id.spinner_minutes);
spin2 =(Spinner)dialog.findViewById(R.id.spinner_minutes2);
spin3 =(Spinner)dialog.findViewById(R.id.spinner_minutes3);
spin4 =(Spinner)dialog.findViewById(R.id.tex);
spin.setOnItemSelectedListener(this);
spin2.setOnItemSelectedListener(this);
spin3.setOnItemSelectedListener(this);
spin4.setOnItemSelectedListener(this);
RadioButton radioButton2 = (RadioButton)dialog.findViewById(R.id.second2);
RadioButton radioButton = (RadioButton)dialog.findViewById(R.id.second);
RadioGroup radioGroup = (RadioGroup)dialog.findViewById(R.id.radioSex);
ArrayAdapter<String> a = new ArrayAdapter<String>(context,R.layout.spinner_item,bankNames);
//ArrayAdapter b = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames2);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(a);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton)dialog.findViewById(checkedId);
if (checkedId == R.id.second2) {
RadioYes();
} else if (checkedId == R.id.second) {
RadioNo();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
((TextView) parent.getChildAt(0)).setTextSize(16);
// Toast.makeText(getApplicationContext(),"" +spin2.getSelectedItem(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void RadioNo(){
spin.setVisibility(View.VISIBLE);
spin2.setVisibility(View.VISIBLE);
spin3.setVisibility(View.VISIBLE);
spin4.setVisibility(View.VISIBLE);
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.VISIBLE);
t3.setVisibility(View.VISIBLE);
t4.setVisibility(View.VISIBLE);
}
public void RadioYes(){
spin.setVisibility(View.GONE);
spin2.setVisibility(View.GONE);
spin3.setVisibility(View.GONE);
spin4.setVisibility(View.GONE);
t1.setVisibility(View.GONE);
t2.setVisibility(View.GONE);
t3.setVisibility(View.GONE);
t4.setVisibility(View.GONE);
}
}
// class to call function show dailoge
public class CustomerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public final int TYPE_MOVIE = 0;
public final int TYPE_LOAD = 1;
static Context context;
List<Customer> customers;
OnLoadMoreListener loadMoreListener;
boolean isLoading = false, isMoreDataAvailable = true;
public CustomerAdapter(Context context, List<Customer> customers) {
this.context = context;
this.customers = customers;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
if(viewType==TYPE_MOVIE){
return new CustomerHolder(inflater.inflate(R.layout.row_movie,parent,false));
}else{
return new LoadHolder(inflater.inflate(R.layout.row_load,parent,false));
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(position>=getItemCount()-1 && isMoreDataAvailable && !isLoading && loadMoreListener!=null){
isLoading = true;
loadMoreListener.onLoadMore();
}
if(getItemViewType(position)==TYPE_MOVIE){
((CustomerHolder)holder).bindData(customers.get(position));
if(((CustomerHolder)holder).buttonViewOption != null)((CustomerHolder)holder).buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Page_6Fragment.newInstance().showDialog(context);
}
});
}
}
#Override
public int getItemViewType(int position) {
if(customers.get(position).type.equals("movie")){
return TYPE_MOVIE;
}else{
return TYPE_LOAD;
}
}
#Override
public int getItemCount(){
return customers.size();
}
/* VIEW HOLDERS */
static class CustomerHolder extends RecyclerView.ViewHolder{
TextView tvTitle;
TextView tvRating;
Button buttonViewOption;
public CustomerHolder(View itemView) {
super(itemView);
tvTitle=(TextView)itemView.findViewById(R.id.title);
tvRating=(TextView)itemView.findViewById(R.id.rating);
buttonViewOption = (Button) itemView.findViewById(R.id.textViewOptions);
}
void bindData(Customer cust){
tvTitle.setText(cust.name);
tvRating.setText(cust.title);
}
}
static class LoadHolder extends RecyclerView.ViewHolder{
public LoadHolder(View itemView) {
super(itemView);
}
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
/* notifyDataSetChanged is final method so we can't override it
call adapter.notifyDataChanged(); after update the list
*/
public void notifyDataChanged(){
notifyDataSetChanged();
isLoading = false;
}
public interface OnLoadMoreListener{
void onLoadMore();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
}

unable to make proper ui like playstore

Hi i am developing an app where i have to make a ui like playtstore for that i saw this tutorial but now my problem is that i'm unable to add different
text for different rows and second is that even after setting height and width it doesnt seem to be get affected.
Please if someone can help me out here i'm stuck at this point
my code is as follows
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int[] images = {R.drawable.vancouver,R.drawable.party,R.drawable.hands_ip,R.drawable.dj};
// Inflate the layout for this fragment
allSampleData = new ArrayList<SectionDataModel>();
createDummyData();
HorizontalAdapter firstAdapter = new HorizontalAdapter(images);
View view = inflater.inflate(R.layout.fragment_home, container, false);
NestedScrollView nestedScrollView = view.findViewById(R.id.scrollView);
llm = new LadderLayoutManager(1.5f, 0.85f, LadderLayoutManager.HORIZONTAL).
setChildDecorateHelper(new LadderLayoutManager
.DefaultChildDecorateHelper(getResources().getDimension(R.dimen.item_max_elevation)));
llm.setChildPeekSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
30, getResources().getDisplayMetrics()));
//llm.setReverse(true);
/*llm.setMaxItemLayoutCount(5);
rcv = (RecyclerView) view.findViewById(R.id.rcv);
rcv.setLayoutManager(llm);
new LadderSimpleSnapHelper().attachToRecyclerView(rcv);
adapter = new HSAdapter();
rcv.setAdapter(adapter);
multi_scroll_recyclerview = (RecyclerView)view.findViewById(R.id.multi_scroll_recyclerview);
multi_scroll_recyclerview.setNestedScrollingEnabled(false);
multi_scroll_layout_manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
multi_scroll_recyclerview.setLayoutManager(multi_scroll_layout_manager);
multi_scroll_adapter = new RecyclerViewDataAdapter(getActivity(),allSampleData);
multi_scroll_recyclerview.setAdapter(multi_scroll_adapter);
multi_scroll_recyclerview.setHasFixedSize(true);*/
/* MultiSnapRecyclerView firstRecyclerView = (MultiSnapRecyclerView)view.findViewById(R.id.first_recycler_view);
LinearLayoutManager firstManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
firstRecyclerView.setLayoutManager(firstManager);
firstRecyclerView.setAdapter(firstAdapter);
HorizontalAdapter secondAdapter = new HorizontalAdapter(images);
MultiSnapRecyclerView secondRecyclerView =(MultiSnapRecyclerView) view.findViewById(R.id.second_recycler_view);
LinearLayoutManager secondManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
secondRecyclerView.setLayoutManager(secondManager);
secondRecyclerView.setAdapter(secondAdapter);
HorizontalAdapter thirdAdapter = new HorizontalAdapter(images);
MultiSnapRecyclerView thirdRecyclerView = (MultiSnapRecyclerView)view.findViewById(R.id.third_recycler_view);
LinearLayoutManager thirdManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
thirdRecyclerView.setLayoutManager(thirdManager);
thirdRecyclerView.setAdapter(thirdAdapter);*/
return view;
}
public void createDummyData() {
for (int i = 1; i <= 5; i++) {
SectionDataModel dm = new SectionDataModel();
dm.setHeaderTitle("Clubs");
dm.setHeadertitle2("Lounge");
dm.setHeadertitle3("Cafe");
dm.setHeadertitle4("Rooftop");
ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
for (int j = 0; j <= 5; j++) {
singleItem.add(new SingleItemModel("Item " + j, "URL " + j));
}
dm.setAllItemsInSection(singleItem);
allSampleData.add(dm);//line which is causing issue
}
}
code for adapter
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SingleItemModel> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModel singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tvTitle;
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
My code for model class
public class SectionDataModel {
private String headerTitle,headertitle2,headertitle3,headertitle4;
private ArrayList<SingleItemModel> allItemsInSection;
public SectionDataModel() {
}
public SectionDataModel(String headerTitle, ArrayList<SingleItemModel> allItemsInSection) {
this.headerTitle = headerTitle;
this.allItemsInSection = allItemsInSection;
}
public String getHeaderTitle() {
return headerTitle;
}
public String getHeadertitle2() {
return headertitle2;
}
public String getHeadertitle3() {
return headertitle3;
}
public String getHeadertitle4() {
return headertitle4;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public void setHeadertitle2(String headertitle2) {
this.headertitle2 = headertitle2;
}
public void setHeadertitle3(String headertitle3) {
this.headertitle3 = headertitle3;
}
public void setHeadertitle4(String headertitle4) {
this.headertitle4 = headertitle4;
}
public ArrayList<SingleItemModel> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<SingleItemModel> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
listitem.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:selectableItemBackground"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.ct.listrtrial.Custom.CustomTextViewMedium
android:id="#+id/itemTitle"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_toLeftOf="#+id/btnMore"
android:text="Sample title"
android:textColor="#android:color/white"
android:textSize="27sp" />
<ImageView
android:id="#+id/btnMore"
android:layout_width="0dp"
android:layout_weight="0.8"
android:layout_marginTop="13dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/ic_more_horiz_black_24dp"
android:textColor="#FFF" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="160dp"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</LinearLayout>
main fragment.xml
<android.support.v4.widget.NestedScrollView android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/scrollView"
android:fillViewport="true"
android:background="#color/colorPrimary"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingTop="10dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/multi_scroll_recyclerview"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
listsinglecard.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="220dp"
android:layout_marginLeft="18dp"
android:layout_height="200dp"
app:cardCornerRadius="65dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:selectableItemBackground"
android:orientation="vertical">
<ImageView
android:id="#+id/itemImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:scaleType="centerCrop"
android:src="#drawable/vancouver" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemImage"
android:gravity="center"
android:padding="5dp"
android:visibility="gone"
android:text="Sample title"
android:textColor="#android:color/black"
android:textSize="18sp" />
</LinearLayout>
</android.support.v7.widget.CardView>

How to remove item from ListView and sharedpreferences android studio?

i want to be able to do this to the code i have already I am new to programing please help.
- Add an icon the user can click (per item) to remove it
- When clicked that item on the list should be removed
-The item should be removed from storage as well (so it doesn't appear next time they load up the app)
here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String Log_TAG = "ToDoApp";
private ToDoListManager listManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
ToDoItemAdapter adapter = new ToDoItemAdapter(
this,
listManager.getList()
);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
listManager.saveList();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
public ToDoItemAdapter(
Context context,
List<ToDoItem> items
) {
super(context, -1, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.item);
CheckBox CheckBox = (CheckBox) convertView.findViewById(R.id.CheckBox);
textView.setText(items.get(position).getDescription());
CheckBox.setChecked(items.get(position).isComplete());
convertView.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) v.getTag();
item.toggleComplete();
notifyDataSetChanged();
}
});
return convertView;
}
}
}
todolistmanager.java
public class ToDoListManager {
private static final String APP_PREFERENCES = "todoapp";
private static final String TODO_ITEMS = "itemslist";
private List<ToDoItem> items;
private SharedPreferences savedData;
public ToDoListManager(Context context) {
savedData = context.getSharedPreferences (
APP_PREFERENCES,
Context.MODE_PRIVATE
);
String json = savedData.getString(TODO_ITEMS, null);
if(json == null) {
items = new ArrayList<>();
} else {
Type type = new TypeToken<List<ToDoItem>>() {}.getType();
items = new Gson().fromJson(json, type);
}
}
public List<ToDoItem> getList() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
saveList();
}
public void saveList() {
SharedPreferences.Editor edit = savedData.edit();
edit.clear();
String json = new Gson().toJson(items);
edit.putString(TODO_ITEMS, json);
edit.apply();
}
}
todoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem(String description,boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
#Override
public String toString() {
return getDescription();
}
}
Activity_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/txtItem"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/hintTxtItem"
/>
<Button
android:id="#+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/lblBtnAdd"
android:layout_toRightOf="#id/txtItem"
/>
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/txtItem"
android:text="#string/txtEmpty"
android:gravity="center_horizontal"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/txtItem"
android:choiceMode="multipleChoice" >
</ListView>
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/lblBtnDel" />
to_do_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<CheckBox
android:id="#+id/CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<ListView
android:layout_weight="20"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/lblBtnDel" />
Step1: Create activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/txtItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text" />
<Button
android:id="#+id/btnAdd"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/txtItem"
android:text="Add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="#+id/lvTodo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice" />
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:text="No data"
android:visibility="invisible" />
</RelativeLayout>
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
Step2: Create to todo_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="10dp"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="#+id/tvTodoName"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Learn Android"
android:textSize="20sp" />
<CheckBox
android:id="#+id/cbChooseTodo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Step3: Define Object Todo
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem(String description, boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isComplete() {
return isComplete;
}
public void setComplete(boolean complete) {
isComplete = complete;
}
}
Step4: Create TodoItemAdapter class
public class TodoItemAdapter extends ArrayAdapter<ToDoItem> {
private ArrayList<ToDoItem> arrayListTodo;
private LayoutInflater layoutInflater;
public TodoItemAdapter(Context context, int resource, ArrayList<ToDoItem> objects) {
super(context, resource, objects);
this.arrayListTodo = objects;
this.layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.todo_item, parent,false);
holder.tvTodoName = (TextView)convertView.findViewById(R.id.tvTodoName);
holder.cbTodoChoose = (CheckBox)convertView.findViewById(R.id.cbChooseTodo);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
final ToDoItem toDoItem = arrayListTodo.get(position);
holder.tvTodoName.setText(toDoItem.getDescription());
holder.cbTodoChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
toDoItem.setComplete(isChecked);
}
});
holder.cbTodoChoose.setChecked(toDoItem.isComplete());
return convertView;
}
public static class ViewHolder{
public TextView tvTodoName;
public CheckBox cbTodoChoose;
}
}
Step5: Process on the MainActivity class
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ListView lvTodoItem;
private ArrayList<ToDoItem> toDoItems;
private TodoItemAdapter todoItemAdapter;
private Button btnDel;
private Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData(){
toDoItems = new ArrayList<>();
todoItemAdapter = new TodoItemAdapter(MainActivity.this, R.layout.todo_item, toDoItems);
lvTodoItem = (ListView)findViewById(R.id.lvTodo);
lvTodoItem.setAdapter(todoItemAdapter);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnDel = (Button)findViewById(R.id.btnDel);
btnAdd.setOnClickListener(this);
btnDel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnAdd:
addTodoItem();
break;
case R.id.btnDel:
deleteTodoItem();
break;
}
}
private void addTodoItem() {
}
private void deleteTodoItem() {
for (int i= toDoItems.size()-1; i>=0 ; i--){
ToDoItem toDoItem = toDoItems.get(i);
if (toDoItem.isComplete()){
toDoItems.remove(i);
}
}
todoItemAdapter.notifyDataSetChanged();
}
}
It is working fine. Thanks.

Categories

Resources