How to add parcelable arraylist to section recycler view adapter - java

In my application i'm trying to pass an parcelable array list to a sectioned recycler view adapter but inside the add method where we add sections it gives me required string error:
This is my parcelable class:
public class HostBean implements Parcelable {
public static final String EXTRA = ActivityMain.PKG + ".extra";
public static final String EXTRA_POSITION = ActivityMain.PKG + ".extra_position";
public static final String EXTRA_HOST = ActivityMain.PKG + ".extra_host";
public static final String EXTRA_TIMEOUT = ActivityMain.PKG + ".network.extra_timeout";
public static final String EXTRA_HOSTNAME = ActivityMain.PKG + ".extra_hostname";
public static final String EXTRA_BANNERS = ActivityMain.PKG + ".extra_banners";
public static final String EXTRA_PORTSO = ActivityMain.PKG + ".extra_ports_o";
public static final String EXTRA_PORTSC = ActivityMain.PKG + ".extra_ports_c";
public static final String EXTRA_SERVICES = ActivityMain.PKG + ".extra_services";
public static final int TYPE_GATEWAY = 0;
public static final int TYPE_COMPUTER = 1;
public int deviceType = TYPE_COMPUTER;
public int isAlive = 1;
public int position = 0;
public int responseTime = 0; // ms
public String ipAddress = null;
public String hostname = null;
public String hostsection = null;
public String hardwareAddress = NetInfo.NOMAC;
public String nicVendor = "Unknown";
public String os = "Unknown";
public HashMap<Integer, String> services = null;
public HashMap<Integer, String> banners = null;
public ArrayList<Integer> portsOpen = null;
public ArrayList<Integer> portsClosed = null;
public HostBean() {
// New object
}
public HostBean(Parcel in) {
// Object from parcel
readFromParcel(in);
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(deviceType);
dest.writeInt(isAlive);
dest.writeString(ipAddress);
dest.writeString(hostname);
dest.writeString( hostsection );
dest.writeString(hardwareAddress);
dest.writeString(nicVendor);
dest.writeString(os);
dest.writeInt(responseTime);
dest.writeInt(position);
dest.writeMap(services);
dest.writeMap(banners);
dest.writeList(portsOpen);
dest.writeList(portsClosed);
}
private void readFromParcel(Parcel in) {
deviceType = in.readInt();
isAlive = in.readInt();
ipAddress = in.readString();
hostname = in.readString();
hardwareAddress = in.readString();
nicVendor = in.readString();
os = in.readString();
hostsection=in.readString();
responseTime = in.readInt();
position = in.readInt();
services = in.readHashMap(null);
banners = in.readHashMap(null);
portsOpen = in.readArrayList(Integer.class.getClassLoader());
portsClosed = in.readArrayList(Integer.class.getClassLoader());
}
#SuppressWarnings("unchecked")
public static final Creator CREATOR = new Creator() {
public HostBean createFromParcel(Parcel in) {
return new HostBean(in);
}
public HostBean[] newArray(int size) {
return new HostBean[size];
}
};
}
This is my simple adapter class:
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> {
private final Context mContext;
private ArrayList<HostBean> mData;
final HostBean host = new HostBean();
public void add(HostBean s,int position) {
position = position == -1 ? getItemCount() : position;
host.hostsection=s;
mData.add(position,s); //at this line of code i'm getting error
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final TextView mac;
public final TextView vendor;
public final TextView ip;
public SimpleViewHolder(View view) {
super(view);
ip = (TextView) view.findViewById(R.id.ip);
mac = (TextView) view.findViewById(R.id.mac);
vendor = (TextView) view.findViewById(R.id.vendor);
}
}
public SimpleAdapter(Context context, List<HostBean> data) {
mContext = context;
if (data != null)
mData = new ArrayList<HostBean>();
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.list_host, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.ip.setText( (CharSequence) mData.get(position) );
holder.mac.setText( "" );
holder.vendor.setText( "" );
}
#Override
public int getItemCount() {
return mData.size();
}
}
This is my simple sectioned recyclerview adapter class:
public class SimpleSectionedRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private static final int SECTION_TYPE = 0;
private boolean mValid = true;
private int mSectionResourceId;
private int mTextResourceId;
private LayoutInflater mLayoutInflater;
private RecyclerView.Adapter mBaseAdapter;
private SparseArray<Section> mSections = new SparseArray<Section>();
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
mBaseAdapter = baseAdapter;
mContext = context;
mBaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
mValid = mBaseAdapter.getItemCount()>0;
notifyDataSetChanged();
}
#Override
public void onItemRangeChanged(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeChanged(positionStart, itemCount);
}
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeInserted(positionStart, itemCount);
}
#Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeRemoved(positionStart, itemCount);
}
});
}
public static class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public SectionViewHolder(View view, int mTextResourceid) {
super(view);
title = (TextView) view.findViewById(mTextResourceid);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int typeView) {
if (typeView == SECTION_TYPE) {
final View view = LayoutInflater.from(mContext).inflate(mSectionResourceId, parent, false);
return new SectionViewHolder(view,mTextResourceId);
}else{
return mBaseAdapter.onCreateViewHolder(parent, typeView -1);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder sectionViewHolder, int position) {
if (isSectionHeaderPosition(position)) {
((SectionViewHolder)sectionViewHolder).title.setText(mSections.get(position).title);
}else{
mBaseAdapter.onBindViewHolder(sectionViewHolder,sectionedPositionToPosition(position));
}
}
#Override
public int getItemViewType(int position) {
return isSectionHeaderPosition(position)
? SECTION_TYPE
: mBaseAdapter.getItemViewType(sectionedPositionToPosition(position)) +1 ;
}
public static class Section {
int firstPosition;
int sectionedPosition;
CharSequence title;
public Section(int firstPosition, CharSequence title) {
this.firstPosition = firstPosition;
this.title = title;
}
public CharSequence getTitle() {
return title;
}
}
public void setSections(Section[] sections) {
mSections.clear();
Arrays.sort(sections, new Comparator<Section>() {
#Override
public int compare(Section o, Section o1) {
return (o.firstPosition == o1.firstPosition)
? 0
: ((o.firstPosition < o1.firstPosition) ? -1 : 1);
}
});
int offset = 0; // offset positions for the headers we're adding
for (Section section : sections) {
section.sectionedPosition = section.firstPosition + offset;
mSections.append(section.sectionedPosition, section);
++offset;
}
notifyDataSetChanged();
}
public int positionToSectionedPosition(int position) {
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).firstPosition > position) {
break;
}
++offset;
}
return position + offset;
}
public int sectionedPositionToPosition(int sectionedPosition) {
if (isSectionHeaderPosition(sectionedPosition)) {
return RecyclerView.NO_POSITION;
}
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).sectionedPosition > sectionedPosition) {
break;
}
--offset;
}
return sectionedPosition + offset;
}
public boolean isSectionHeaderPosition(int position) {
return mSections.get(position) != null;
}
#Override
public long getItemId(int position) {
return isSectionHeaderPosition(position)
? Integer.MAX_VALUE - mSections.indexOfKey(position)
: mBaseAdapter.getItemId(sectionedPositionToPosition(position));
}
#Override
public int getItemCount() {
return (mValid ? mBaseAdapter.getItemCount() + mSections.size() : 0);
}
}
This is how is initialize the arraylist:
hosts = new ArrayList<HostBean>();
This is my activity code for setting adapter to recyclerview:
RecyclerView list =findViewById(R.id.output);
list.setHasFixedSize( true );
list.setLayoutManager( new LinearLayoutManager( this ) );
list.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
SimpleAdapter mAdapter = new SimpleAdapter(this,hosts);
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0,"Know Devices"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5,"Unknown Devices"));
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(this,R.layout.section,R.id.section_text,mAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
list.setAdapter( mSectionedAdapter );

Your mData is an ArrayList<>. Therefore you can not pass key, value for that. You can only pass one param, either key or value. List is not a map.
private ArrayList<HostBean> mData;
mData.add(position,s); // Can not do this
If you want a key value relationship, then use HashMap like this.
private HashMap<Integer, HostBean> mData;

Related

How can I save a list within a list using the room persistence library? (android & Java)

how are you, I hope everyone is fine
I have created an application to generate a sales invoice.
In SalesInvoiceActivity, when the user clicks on the FloatingActionButton, it goes to AddSaleInvoiceActivity.
addSaleInvoiceFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(SalesInvoiceActivity.this, AddSaleInvoiceActivity.class));
}
});
In AddSaleInvoiceActivity there is an EditText and Date to store the name of the customer and invoice date in RecyclerView list in SalesInvoiceActivity.
customerName = addCustomerNameEt.getText().toString();
date = new Date();
When the user presses the Save Invoice button, the invoice number is saved with the ID, the invoice date, and the customer's name.
final SaleInvoiceEntry saleInvoiceEntry = new SaleInvoiceEntry(customerName, date);
appDatabase.salesInvoiceDao().insertSaleInvoice(saleInvoiceEntry);
#Entity(tableName = "saleInvoice")
public class SaleInvoiceEntry {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "customerName")
private String customerName;
#ColumnInfo(name = "invoiceDate")
private Date invoiceDate;
#Ignore
public SaleInvoiceEntry(String customerName, Date invoiceDate) {
this.customerName = customerName;
this.invoiceDate = invoiceDate;
}
public SaleInvoiceEntry(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerName() {
return customerName;
}
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public Date getInvoiceDate() {
return invoiceDate;
}
}
#Dao
public interface SalesInvoiceDao {
#Query("SELECT * FROM saleInvoice ORDER BY id")
LiveData<List<SaleInvoiceEntry>> loadAllSalesInvoice();
#Query("SELECT * FROM saleInvoice WHERE id = :saleInvoiceId")
LiveData<SaleInvoiceEntry> loadSalesInvoiceById(int saleInvoiceId);
#Insert
void insertSaleInvoice(SaleInvoiceEntry saleInvoiceEntry);
#Update(onConflict = OnConflictStrategy.REPLACE)
void updateSaleInvoice(SaleInvoiceEntry saleInvoiceEntry);
#Delete
void deleteSaleInvoice(SaleInvoiceEntry saleInvoiceEntry);
}
public class SalesInvoiceAdapter extends RecyclerView.Adapter<SalesInvoiceAdapter.SalesInvoiceViewHolder>
implements AddProductToSaleInvoiceAdapter.ItemClickListener {
private static final String DATE_FORMAT = "dd/MM/yyy";
private final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
private final ItemClickListener itemClickListener;
private List<SaleInvoiceEntry> saleInvoiceEntries;
private final Context context;
private AppDatabase appDatabase;
private String saleInvoiceNumber, customerName, saleInvoiceDate;
public SalesInvoiceAdapter(Context context, ItemClickListener listener, AppDatabase appDatabase) {
this.context = context;
itemClickListener = listener;
this.appDatabase = appDatabase;
}
#NonNull
#Override
public SalesInvoiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.sales_list, parent, false);
return new SalesInvoiceViewHolder(view);
}
#SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
#Override
public void onBindViewHolder(SalesInvoiceViewHolder salesInvoiceViewHolder, int saleInvoicePosition) {
SaleInvoiceEntry saleInvoiceEntry = saleInvoiceEntries.get(saleInvoicePosition);
saleInvoiceNumber = String.valueOf(saleInvoiceEntry.getId());
salesInvoiceViewHolder.saleInvoiceNumberView.setText(context.getString(R.string.sale_invoice_number) + " : " + saleInvoiceNumber);
customerName = saleInvoiceEntry.getCustomerName();
salesInvoiceViewHolder.customerNameView.setText(context.getString(R.string.customer_name) + " : " + customerName);
saleInvoiceDate = dateFormat.format(saleInvoiceEntry.getInvoiceDate());
salesInvoiceViewHolder.saleInvoiceDateView.setText(context.getString(R.string.invoice_date) + " : " + saleInvoiceDate);
appDatabase = AppDatabase.getInstance(context);
salesInvoiceViewHolder.deleteSaleInvoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context, R.style.CutShapeTheme);
builder.setTitle(context.getString(R.string.delete_invoice))
.setMessage(context.getString(R.string.delete_invoice_message))
.setPositiveButton(context.getString(R.string.yes), (dialogInterface, i) -> {
try {
AppExecutors.getInstance().diskIO().execute(new Runnable() {
#Override
public void run() {
int saleInvoicePosition = salesInvoiceViewHolder.getAdapterPosition();
appDatabase.salesInvoiceDao().deleteSaleInvoice(saleInvoiceEntries.get(saleInvoicePosition));
}
});
Toast.makeText(context, context.getString(R.string.invoice_deleted), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
})
.setCancelable(false)
.setNegativeButton(context.getString(R.string.no), (dialog, which) -> {
})
.create().show();
}
});
salesInvoiceViewHolder.editSaleInvoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent saleInvoiceIntent = new Intent(context, AddSaleInvoiceActivity.class);
int saleInvoiceId = saleInvoiceEntries.get(salesInvoiceViewHolder.getAdapterPosition()).getId();
saleInvoiceIntent.putExtra(EXTRA_SALE_INVOICE_ID, saleInvoiceId);
context.startActivity(saleInvoiceIntent);
}
});
}
#Override
public int getItemCount() {
if (saleInvoiceEntries == null) {
return 0;
}
return saleInvoiceEntries.size();
}
public List<SaleInvoiceEntry> getSaleInvoiceEntries() {
return saleInvoiceEntries;
}
#SuppressLint("NotifyDataSetChanged")
public void setSaleInvoiceEntries(List<SaleInvoiceEntry> saleInvoiceEntries) {
this.saleInvoiceEntries = saleInvoiceEntries;
notifyDataSetChanged();
}
#Override
public void onItemClickListener(int productId, String productName) {
}
public interface ItemClickListener {
void onItemClickListener(int saleInvoiceId, String customerName);
}
class SalesInvoiceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView saleInvoiceNumberView, customerNameView, saleInvoiceDateView;
private final ImageView deleteSaleInvoice, editSaleInvoice;
public SalesInvoiceViewHolder(View itemView) {
super(itemView);
saleInvoiceNumberView = itemView.findViewById(R.id.listInvoiceNumber);
customerNameView = itemView.findViewById(R.id.listCustomerName);
saleInvoiceDateView = itemView.findViewById(R.id.listInvoiceDate);
deleteSaleInvoice = itemView.findViewById(R.id.listDeleteSaleInvoice);
editSaleInvoice = itemView.findViewById(R.id.listEditSaleInvoice);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int saleInvoiceId = saleInvoiceEntries.get(getAdapterPosition()).getId();
String customerName = saleInvoiceEntries.get(getAdapterPosition()).getCustomerName();
itemClickListener.onItemClickListener(saleInvoiceId, customerName);
}
}
}
public class SalesInvoiceActivity extends AppCompatActivity implements SalesInvoiceAdapter.ItemClickListener {
private FloatingActionButton addSaleInvoiceFab;
private RecyclerView salesInvoiceRv;
private SalesInvoiceAdapter salesInvoiceAdapter;
private AppDatabase appDatabase;
private View salesInvoiceEmptyView;
private SearchView salesInvoiceSv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_invoice);
initSalesInvoiceView();
setupSalesInvoiceViewModel();
setupSalesInvoiceRecycleView();
addSaleInvoiceFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(SalesInvoiceActivity.this, AddSaleInvoiceActivity.class));
}
});
salesInvoiceSv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
setupSalesInvoiceViewModel();
salesInvoiceFilter(newText);
return true;
}
});
}
private void salesInvoiceFilter(String text) {
ArrayList<SaleInvoiceEntry> salesInvoiceList = new ArrayList<>();
for (SaleInvoiceEntry saleInvoice : salesInvoiceAdapter.getSaleInvoiceEntries()) {
if (saleInvoice.getCustomerName().toLowerCase().contains(text.toLowerCase())) {
salesInvoiceList.add(saleInvoice);
}
}
if (salesInvoiceList.isEmpty()) {
Toast.makeText(this, getString(R.string.no_invoice), Toast.LENGTH_SHORT).show();
} else {
salesInvoiceAdapter.setSaleInvoiceEntries(salesInvoiceList);
}
}
private void initSalesInvoiceView() {
salesInvoiceEmptyView = findViewById(R.id.salesInvoiceEmptyView);
addSaleInvoiceFab = findViewById(R.id.addSaleInvoiceFab);
salesInvoiceRv = findViewById(R.id.salesInvoiceRv);
salesInvoiceSv = findViewById(R.id.saleSearchView);
}
private void setupSalesInvoiceRecycleView() {
appDatabase = AppDatabase.getInstance(getApplicationContext());
salesInvoiceAdapter = new SalesInvoiceAdapter(this, this, appDatabase);
salesInvoiceRv.setHasFixedSize(true);
salesInvoiceRv.setLayoutManager(new LinearLayoutManager(this));
salesInvoiceRv.setAdapter(salesInvoiceAdapter);
}
private void setupSalesInvoiceViewModel() {
MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mainViewModel.getListSalesInvoiceLiveData().observe(this, new Observer<List<SaleInvoiceEntry>>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onChanged(#Nullable List<SaleInvoiceEntry> saleInvoiceEntries) {
salesInvoiceAdapter.setSaleInvoiceEntries(saleInvoiceEntries);
salesInvoiceAdapter.notifyDataSetChanged();
if (salesInvoiceAdapter.getItemCount() == 0) {
salesInvoiceRv.setVisibility(View.GONE);
salesInvoiceEmptyView.setVisibility(View.VISIBLE);
salesInvoiceSv.setVisibility(View.GONE);
} else {
salesInvoiceRv.setVisibility(View.VISIBLE);
salesInvoiceEmptyView.setVisibility(View.GONE);
salesInvoiceSv.setVisibility(View.VISIBLE);
}
}
});
}
#Override
public void onItemClickListener(int saleInvoiceId, String customerName) {
Intent intent = new Intent(SalesInvoiceActivity.this, SaleDetailsActivity.class);
intent.putExtra("saleInvoiceId", saleInvoiceId);
intent.putExtra("productName", customerName);
startActivity(intent);
}
}
In AddSaleInvoiceActivity, I created a button that when the user clicks on it, it will be directed to the product store to capture the name of the product, selling price and store it in the RecyclerView list inside AddSaleInvoiceActivity
private Button addProductToSaleInvoiceBtn;
private void initAddProductToSaleInvoiceViews() {
addProductToSaleInvoiceBtn = findViewById(R.id.addProductToSaleInvoiceBtn);
addProductToSaleInvoiceBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent productToSaleInvoiceIntent = new Intent(AddSaleInvoiceActivity.this, ProductStoreActivity.class);
productToSaleInvoiceIntent.putExtra(EXTRA_PRODUCT_TO_SALE_INVOICE_ID, 1);
startActivity(productToSaleInvoiceIntent);
}
});
productToSaleInvoiceRv = findViewById(R.id.productToSaleInvoiceRv);
addProductToSaleInvoiceAdapter = new AddProductToSaleInvoiceAdapter(this, this, appDatabase);
productToSaleInvoiceRv.setHasFixedSize(true);
productToSaleInvoiceRv.setLayoutManager(new LinearLayoutManager(this));
productToSaleInvoiceRv.setAdapter(addProductToSaleInvoiceAdapter);
MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mainViewModel.getListToSalesInvoiceLiveData().observe(this, new Observer<List<AddProductToSalesInvoiceEntry>>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onChanged(#Nullable List<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceEntries) {
addProductToSaleInvoiceAdapter.setProductToSalesInvoiceEntries(addProductToSalesInvoiceEntries);
addProductToSaleInvoiceAdapter.notifyDataSetChanged();
}
});
}
#Entity(tableName = "addProductToSalesInvoice")
public class AddProductToSalesInvoiceEntry {
#PrimaryKey(autoGenerate = true)
private int addProductToSalesInvoiceId;
private final String toSalesInvoiceProductName;
private final int toSalesInvoiceProductQuantity;
private final float toSalesInvoiceProductSellingPrice;
#Ignore
public AddProductToSalesInvoiceEntry(String toSalesInvoiceProductName, int toSalesInvoiceProductQuantity
, float toSalesInvoiceProductSellingPrice) {
this.toSalesInvoiceProductName = toSalesInvoiceProductName;
this.toSalesInvoiceProductQuantity = toSalesInvoiceProductQuantity;
this.toSalesInvoiceProductSellingPrice = toSalesInvoiceProductSellingPrice;
}
public AddProductToSalesInvoiceEntry(int addProductToSalesInvoiceId, String toSalesInvoiceProductName, int toSalesInvoiceProductQuantity
, float toSalesInvoiceProductSellingPrice) {
this.addProductToSalesInvoiceId = addProductToSalesInvoiceId;
this.toSalesInvoiceProductName = toSalesInvoiceProductName;
this.toSalesInvoiceProductQuantity = toSalesInvoiceProductQuantity;
this.toSalesInvoiceProductSellingPrice = toSalesInvoiceProductSellingPrice;
}
public int getAddProductToSalesInvoiceId() {
return addProductToSalesInvoiceId;
}
public void setAddProductToSalesInvoiceId(int addProductToSalesInvoiceId) {
this.addProductToSalesInvoiceId = addProductToSalesInvoiceId;
}
public String getToSalesInvoiceProductName() {
return toSalesInvoiceProductName;
}
public int getToSalesInvoiceProductQuantity() {
return toSalesInvoiceProductQuantity;
}
public float getToSalesInvoiceProductSellingPrice() {
return toSalesInvoiceProductSellingPrice;
}
}
#Dao
public interface AddProductToSalesInvoiceDao {
#Query("SELECT * FROM addProductToSalesInvoice ORDER BY addProductToSalesInvoiceId")
LiveData<List<AddProductToSalesInvoiceEntry>> addProductToSalesInvoiceLoadAllProducts();
#Query("SELECT * FROM addProductToSalesInvoice WHERE addProductToSalesInvoiceId = :addProductToSalesInvoiceProductId")
LiveData<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceLoadProductsById(int addProductToSalesInvoiceProductId);
#Insert
void addProductToSalesInvoiceInsertProduct(AddProductToSalesInvoiceEntry addProductToSalesInvoiceEntry);
#Update(onConflict = OnConflictStrategy.REPLACE)
void addProductToSalesInvoiceUpdateProduct(AddProductToSalesInvoiceEntry addProductToSalesInvoiceEntry);
#Delete
void addProductToSalesInvoiceDeleteProduct(AddProductToSalesInvoiceEntry addProductToSalesInvoiceEntry);
#Delete
void addProductToSalesInvoiceDeleteAllProduct(List<AddProductToSalesInvoiceEntry> toSalesInvoiceEntries);
}
public class AddProductToSaleInvoiceAdapter extends RecyclerView
.Adapter<AddProductToSaleInvoiceAdapter.AddProductToSalesInvoiceViewHolder> {
private final ItemClickListener addProductToSalesInvoiceItemClickListener;
private List<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceEntries;
private final Context context;
private AppDatabase appDatabase;
private String addProductToSalesInvoiceProductName;
private int addProductToSalesInvoiceProductQuantity;
private float addProductToSalesInvoiceProductSellingPrice;
private List<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceEntryList;
public AddProductToSaleInvoiceAdapter(Context context, ItemClickListener listener, AppDatabase appDatabase) {
this.context = context;
addProductToSalesInvoiceItemClickListener = listener;
this.appDatabase = appDatabase;
}
#NonNull
#Override
public AddProductToSalesInvoiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.add_products_to_sale_invoice_list, parent, false);
return new AddProductToSalesInvoiceViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(AddProductToSalesInvoiceViewHolder addProductToSalesInvoiceViewHolder
, int productToSalesInvoicePosition) {
AddProductToSalesInvoiceEntry addProductToSalesInvoiceEntry
= addProductToSalesInvoiceEntries.get(productToSalesInvoicePosition);
addProductToSalesInvoiceProductName = addProductToSalesInvoiceEntry.getToSalesInvoiceProductName();
addProductToSalesInvoiceViewHolder.listAddProductToSalesInvoiceProductNameView.setText(addProductToSalesInvoiceProductName);
addProductToSalesInvoiceProductQuantity = addProductToSalesInvoiceEntry.getToSalesInvoiceProductQuantity();
addProductToSalesInvoiceViewHolder.listAddProductToSalesInvoiceProductQuantityView.setText("" + addProductToSalesInvoiceProductQuantity);
addProductToSalesInvoiceProductSellingPrice = addProductToSalesInvoiceEntry.getToSalesInvoiceProductSellingPrice();
addProductToSalesInvoiceViewHolder.listAddProductToSalesInvoiceProductSellingPriceView.setText("" + addProductToSalesInvoiceProductSellingPrice);
addProductToSalesInvoiceViewHolder.productSellingPriceView.setText(context.getString(R.string.product_selling_price) + " : " + addProductToSalesInvoiceProductSellingPrice);
#Override
public int getItemCount() {
if (addProductToSalesInvoiceEntries == null) {
return 0;
}
return addProductToSalesInvoiceEntries.size();
}
public List<AddProductToSalesInvoiceEntry> getAddProductToSalesInvoiceEntries
(ArrayList<AddProductToSalesInvoiceEntry> uProductToSalesInvoiceList) {
return addProductToSalesInvoiceEntries;
}
#SuppressLint("NotifyDataSetChanged")
public void setProductToSalesInvoiceEntries(List<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceEntries) {
this.addProductToSalesInvoiceEntries = addProductToSalesInvoiceEntries;
notifyDataSetChanged();
}
public interface ItemClickListener {
void onItemClickListener(int productId, String productName);
}
class AddProductToSalesInvoiceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView listAddProductToSalesInvoiceProductNameView, listAddProductToSalesInvoiceProductQuantityView
, listAddProductToSalesInvoiceProductSellingPriceView;
public AddProductToSalesInvoiceViewHolder(View itemView) {
super(itemView);
listAddProductToSalesInvoiceProductNameView = itemView
.findViewById(R.id.listAddProductToSalesInvoiceProductNameView);
listAddProductToSalesInvoiceProductQuantityView = itemView
.findViewById(R.id.listAddProductToSalesInvoiceProductQuantityView);
listAddProductToSalesInvoiceProductSellingPriceView = itemView
.findViewById(R.id.listAddProductToSalesInvoiceProductSellingPriceView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int productId = addProductToSalesInvoiceEntries.get(getAdapterPosition()).getAddProductToSalesInvoiceId();
String productName = addProductToSalesInvoiceEntries.get(getAdapterPosition()).getToSalesInvoiceProductName();
addProductToSalesInvoiceItemClickListener.onItemClickListener(productId, productName);
}
}
}
Now how do I store the AddProductToSalesInvoiceEntry list inside the SaleInvoiceEntry list when the user clicks the save invoice button ?

Add different layout between item in RecyclerView-AndroidX

I want to add Different layout between item in my recyclerview, I have 3 item in first layout, and then I add second layout to item number 2, so It should have 4 item right now, (1-FirstLayout)-(2-SecondLayout)-(3FirstLayout)-(4FirstLayout), but I realize the position that I choose from my second layout replaced to the position first layout it becomes like this (1-FirstLayout)-(2-SecondLayout)-(3FirstLayout)
Iam not sure how to fix it
This is my Adapter
public class AdapterGameReview extends RecyclerView.Adapter{
public static final int TYPE_ITEM = 1;
public static final int TYPE_TOPREVIEWER = 2;
public static final int TYPE_ADSBANNER = 3;
private boolean mWithTopReviewer = true;
private boolean mWithAdsBanner = false;
private Context mContext;
private ArrayList<ModelGameReview> modelGameReviews;
private RecyclerViewClickListener mListener;
public AdapterGameReview(Context mContext, ArrayList<ModelGameReview> modelGameReviews, RecyclerViewClickListener mListener) {
this.mContext = mContext;
this.modelGameReviews = modelGameReviews;
this.mListener = mListener;
}
//Container
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = null;
if (viewType == TYPE_TOPREVIEWER) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gamereviewtopreviewer, null);
return new GameReviewTopReviewerViewHolder(v);
} else if (viewType == TYPE_ADSBANNER) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_adsbannerdummy, null);
return new GameReviewAdsBannerViewHolder(v);
} else {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gamereview, null);
return new GameReviewViewHolder(v, mListener);
}
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof AdapterGameReview.GameReviewTopReviewerViewHolder) {
AdapterGameReview.GameReviewTopReviewerViewHolder gameReviewTopReviewerViewHolder = (AdapterGameReview.GameReviewTopReviewerViewHolder) holder;
/*gameReviewTopReviewerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});*/
}else if (holder instanceof AdapterGameReview.GameReviewAdsBannerViewHolder) {
AdapterFollowSavedGameReviewList.ShowmoreViewHolder showmoreViewHolder = (AdapterFollowSavedGameReviewList.ShowmoreViewHolder) holder;
} else {
final GameReviewViewHolder GameReviewViewHolder = (GameReviewViewHolder) holder;
final ModelGameReview modelGameReviewX = modelGameReviews.get(position);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.mipmap.ic_launcher);
requestOptions.error(R.drawable.bug);
requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
requestOptions.centerCrop();
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = inputFormat.parse(modelGameReviewX.getGamedate());
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence niceDateStr = DateUtils.getRelativeTimeSpanString(date.getTime(), Calendar.getInstance().getTimeInMillis(), DateUtils.MINUTE_IN_MILLIS);
//Set
GameReviewViewHolder.TVGameDate.setText(niceDateStr);
GameReviewViewHolder.TVGameTitle.setText(modelGameReviewX.getGametitle());
GameReviewViewHolder.TVGameDescription.setText(modelGameReviewX.getGamedescription());
Glide.with(mContext).load(modelGameReviewX.getGameimage())
.apply(requestOptions)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
GameReviewViewHolder.ProgressLoadPhoto.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
GameReviewViewHolder.ProgressLoadPhoto.setVisibility(View.GONE);
return false;
}
})
.transition(DrawableTransitionOptions.withCrossFade())
.into(GameReviewViewHolder.IMGGameImage);
GameReviewViewHolder.TVSeenCounter.setText(String.valueOf(modelGameReviewX.getSeencounter()));
GameReviewViewHolder.TVCommentCounter.setText(String.valueOf(modelGameReviewX.getCommentcounter()));
GameReviewViewHolder.TVLikeCounter.setText(String.valueOf(modelGameReviewX.getLikecounter()));
if (modelGameReviewX.getIscomment() == 0) {
GameReviewViewHolder.IMGCommentView.setImageResource(R.drawable.comment_off);
} else if (modelGameReviewX.getIscomment() == 1) {
GameReviewViewHolder.IMGCommentView.setImageResource(R.drawable.comment_on);
}
if (modelGameReviewX.getIslike() == 0) {
GameReviewViewHolder.IMGLikeView.setImageResource(R.drawable.heart_off);
} else if (modelGameReviewX.getIslike() == 1) {
GameReviewViewHolder.IMGLikeView.setImageResource(R.drawable.heart_on);
}
if (modelGameReviewX.getIsbookmark() == 0) {
GameReviewViewHolder.IMGBookmarkView.setImageResource(R.drawable.saved_off);
GameReviewViewHolder.IMGBookmarkView.setVisibility(View.GONE);
} else if (modelGameReviewX.getIsbookmark() == 1) {
GameReviewViewHolder.IMGBookmarkView.setImageResource(R.drawable.saved_on);
}
GameReviewViewHolder.TVReviewer.setText(modelGameReviewX.getReviewer());
}
}
#Override
public int getItemCount() {
int itemCount = 0;
if(mWithTopReviewer == true){
itemCount++;
}
itemCount = modelGameReviews.size();
return itemCount;
}
//TYPE_ITEM
public class GameReviewViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView TVGameDate;
TextView TVGameTitle;
TextView TVGameDescription;
ImageView IMGGameImage;
TextView TVSeenCounter;
TextView TVCommentCounter;
TextView TVLikeCounter;
ImageView IMGSeenView;
ImageView IMGCommentView;
ImageView IMGLikeView;
TextView TVReviewer;
ProgressBar ProgressLoadPhoto;
ImageView IMGBookmarkView;
private RelativeLayout ROWGameReviewContainer;
private RecyclerViewClickListener mListener;
public GameReviewViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameTitle = itemView.findViewById(R.id.TV_GameTitle);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
TVSeenCounter = itemView.findViewById(R.id.TV_SeenCounter);
TVCommentCounter = itemView.findViewById(R.id.TV_CommentCounter);
TVLikeCounter = itemView.findViewById(R.id.TV_LikeCounter);
IMGSeenView = itemView.findViewById(R.id.IMG_SeenView);
IMGCommentView = itemView.findViewById(R.id.IMG_CommentView);
IMGLikeView = itemView.findViewById(R.id.IMG_LikeView);
TVReviewer = itemView.findViewById(R.id.TV_Reviewer);
ProgressLoadPhoto = itemView.findViewById(R.id.Progress_LoadPhoto);
IMGBookmarkView = itemView.findViewById(R.id.IMG_BookmarkView);
ROWGameReviewContainer = itemView.findViewById(R.id.ROW_GameReviewContainer);
mListener = listener;
ROWGameReviewContainer.setOnClickListener(this);
IMGCommentView.setOnClickListener(this);
IMGLikeView.setOnClickListener(this);
IMGBookmarkView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ROW_GameReviewContainer:
mListener.onRowGameReviewContainerClick(ROWGameReviewContainer, getAdapterPosition());
break;
case R.id.IMG_CommentView:
mListener.onRowCommentViewClick(IMGCommentView, getAdapterPosition());
break;
case R.id.IMG_LikeView:
mListener.onRowLikeViewClick(IMGLikeView, getAdapterPosition());
break;
case R.id.IMG_BookmarkView:
mListener.onRowBookmarkViewClick(IMGBookmarkView, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowGameReviewContainerClick(View view, int position);
void onRowCommentViewClick(View view, int position);
void onRowLikeViewClick(View view, int position);
void onRowBookmarkViewClick(View view, int position);
}
//TYPE_TOPREVIEWER
public class GameReviewTopReviewerViewHolder extends RecyclerView.ViewHolder{
Button BTNToBeReviewer;
public GameReviewTopReviewerViewHolder(View itemView) {
super(itemView);
BTNToBeReviewer = itemView.findViewById(R.id.BTN_ToBeReviewer);
}
}
//TYPE_ADSBANNER
public class GameReviewAdsBannerViewHolder extends RecyclerView.ViewHolder{
public GameReviewAdsBannerViewHolder(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (mWithTopReviewer && isPositionTopReviewer(position))
return TYPE_TOPREVIEWER;
if (mWithAdsBanner && isPositionAdsBanner(position))
return TYPE_ADSBANNER;
return TYPE_ITEM;
}
public boolean isPositionTopReviewer(int position) {
return position == 1 && mWithTopReviewer;
}
public boolean isPositionAdsBanner(int position) {
return position == getItemCount() - 1 && mWithAdsBanner;
}
public void setWithTopReviewer(boolean value) {
mWithTopReviewer = value;
}
public void setWithAdsBanner(boolean value) {
mWithAdsBanner = value;
}
}
This is My Model
public class ModelGameReview implements Serializable {
private int contentpage;
private String idcontent;
private String gametitle;
private String gamedate;
private String gameimage;
private String gamedescription;
private int seencounter;
private int commentcounter;
private int likecounter;
private int iscomment;
private int islike;
private int isbookmark;
private String reviewer;
private String value;
private String message;
public ModelGameReview(int contentpage, String idcontent, String gametitle, String gamedate, String gameimage, String gamedescription, int seencounter, int commentcounter, int likecounter, int iscomment, int islike, int isbookmark, String reviewer, String value, String message) {
this.contentpage = contentpage;
this.idcontent = idcontent;
this.gametitle = gametitle;
this.gamedate = gamedate;
this.gameimage = gameimage;
this.gamedescription = gamedescription;
this.seencounter = seencounter;
this.commentcounter = commentcounter;
this.likecounter = likecounter;
this.iscomment = iscomment;
this.islike = islike;
this.isbookmark = isbookmark;
this.reviewer = reviewer;
this.value = value;
this.message = message;
}
public int getContentpage() {
return contentpage;
}
public void setContentpage(int contentpage) {
this.contentpage = contentpage;
}
public String getIdcontent() {
return idcontent;
}
public void setIdcontent(String idcontent) {
this.idcontent = idcontent;
}
public String getGametitle() {
return gametitle;
}
public void setGametitle(String gametitle) {
this.gametitle = gametitle;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGameimage() {
return gameimage;
}
public void setGameimage(String gameimage) {
this.gameimage = gameimage;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getSeencounter() {
return seencounter;
}
public void setSeencounter(int seencounter) {
this.seencounter = seencounter;
}
public int getCommentcounter() {
return commentcounter;
}
public void setCommentcounter(int commentcounter) {
this.commentcounter = commentcounter;
}
public int getLikecounter() {
return likecounter;
}
public void setLikecounter(int likecounter) {
this.likecounter = likecounter;
}
public int getIscomment() {
return iscomment;
}
public void setIscomment(int iscomment) {
this.iscomment = iscomment;
}
public int getIslike() {
return islike;
}
public void setIslike(int islike) {
this.islike = islike;
}
public int getIsbookmark() {
return isbookmark;
}
public void setIsbookmark(int isbookmark) {
this.isbookmark = isbookmark;
}
public String getReviewer() {
return reviewer;
}
public void setReviewer(String reviewer) {
this.reviewer = reviewer;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
You have implemented this method wrong
#Override
public int getItemCount() {
int itemCount = 0;
if(mWithTopReviewer == true){
itemCount++;
}
itemCount = modelGameReviews.size();
return itemCount;
}
It should be something similar
#Override
public int getItemCount() {
int itemCount = modelGameReviews.size();
if(mWithTopReviewer == true){
itemCount++;
}
return itemCount;
}

new item is not getting added in recyclerview?

i am scanning devices from a bluetooth and getting their data from their advertisement,so one of the device gives the data of other devices which is not in ranged from the mobile device,so i specifically filter the data of that device which i wanted to show in recycler view in automatically updating the rssi values.
let's say,
a device A which gives the data of 3 devices B,C,D containing their rssi values continuously,so what i want to show the list of device B,C,D with their rssi values which is changing continuously.
What i have done until now is scan that device "A",and extract the data of B and shown in recyclerview,but when another device i.e C's data comes in the old device i.e B got vanished and so on.
what i want is continuously changing data of B,C,D.
Adapter Class:-
public class ReapeaterDeviceAdapter extends RecyclerView.Adapter<ReapeaterDeviceAdapter.CryptoViewHolder> {
private ArrayList<RepeaterModel> data = new ArrayList<>();;
private Context mCtx;
public class CryptoViewHolder extends RecyclerView.ViewHolder {
private TextView mName, mPrice;
public CryptoViewHolder(View itemView) {
super(itemView);
mName = itemView.findViewById(R.id.txtName);
mPrice = itemView.findViewById(R.id.txtPrice);
}
}
public ReapeaterDeviceAdapter(Context ctx,ArrayList<RepeaterModel> data) {
this.mCtx = ctx;
this.data = data;
}
#Override
public CryptoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.repeater_dev_data,parent, false);
return new CryptoViewHolder(itemView);
}
#Override
public void onBindViewHolder(CryptoViewHolder holder, int position) {
System.out.println("onBinder");
holder.mName.setText(data.get(position).macdev);
holder.mPrice.setText(String.valueOf(data.get(position).rssi));
}
#Override
public void onBindViewHolder(CryptoViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
//System.out.println("onbinder");
super.onBindViewHolder(holder, position, payloads);
} else {
Bundle o = (Bundle) payloads.get(0);
//System.out.println("in keyset");
for (String key : o.keySet()) {
if (key.equals("price")) {
holder.mName.setText(data.get(position).macdev);
holder.mPrice.setText(String.valueOf(data.get(position).rssi));
//holder.mPrice.setTextColor(Color.GREEN);
//this.notifyItemChanged(position);
}
}
}
}
#Override
public int getItemCount() {
return data.size();
}
public ArrayList<RepeaterModel> getData() {
return data;
}
public void setData(ArrayList<RepeaterModel> newData) {
MyDiffUtilCallBack diffCallBack = new MyDiffUtilCallBack(newData, this.data);
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallBack);
//this.setData(newData);
// this.data=newData;
this.data.clear();
// this.data = newData;
this.data.addAll(newData);
diffResult.dispatchUpdatesTo(this);
//this.notifyItemRangeChanged(0, this.getItemCount());
//this.notifyDataSetChanged();
//System.out.println("Here");
}
}
Model Class:-
public String macdev;
public int rssi ;
public int imageid;
public RepeaterModel(String macdev, int rssi, int imageid) {
this.macdev = macdev;
this.rssi = rssi;
this.imageid = imageid;
}
public String getMacdev() {
return macdev;
}
public void setMacdev(String macdev) {
this.macdev = macdev;
}
public int getRssi() {
return rssi;
}
public void setRssi(int rssi) {
this.rssi = rssi;
}
public int getImageid() {
return imageid;
}
public void setImageid(int imageid) {
this.imageid = imageid;
}
#Override
public boolean equals(Object o) {
System.out.println("in equals");
if (this == o) return true;
if (!(o instanceof RepeaterModel)) return false;
RepeaterModel that = (RepeaterModel) o;
return getRssi() == that.getRssi() &&
getImageid() == that.getImageid() &&
getMacdev().equals(that.getMacdev());
}
#Override
public int hashCode() {
return Objects.hash(getMacdev(), getRssi(), getImageid());
}
/*#Override
public int hashCode() {
int result = Integer.valueOf(rssi);
// result = result + (imageid != 0 ? imageid.hashCode() : 0);
result = result + rssi.hashCode();
System.out.println("hash");
return result;
}*/
}
Diffutilcallback :-
ArrayList<RepeaterModel> newList;
ArrayList<RepeaterModel> oldList;
public MyDiffUtilCallBack(ArrayList<RepeaterModel> newList, ArrayList<RepeaterModel> oldList) {
this.newList = newList;
this.oldList = oldList;
}
#Override
public int getOldListSize() {
return oldList != null ? oldList.size() : 0;
}
#Override
public int getNewListSize() {
return newList != null ? newList.size() : 0;
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
if(newList.get(newItemPosition).getMacdev().equals(oldList.get(oldItemPosition).getMacdev()))
{
// Log.d("itemsame","in same");
return true;
}
else {
// Log.d("itemsame", "not same");
}
return false;
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition)
{
//System.out.println("in content same");
final RepeaterModel oldRepeater = oldList.get(oldItemPosition);
final RepeaterModel newRepeater = newList.get(newItemPosition);
if(oldRepeater.getRssi()!=(newRepeater.getRssi()))
{
//Log.d("item contenets","content different");
return false;
}
//Log.d("item contenets","content same");
return true;
}
#Nullable
#Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
RepeaterModel newModel = newList.get(newItemPosition);
RepeaterModel oldModel = oldList.get(oldItemPosition);
//System.out.println("getchange");
Bundle diff = new Bundle();
//if (newModel.getMacdev().equals(oldModel.getMacdev()))
//{
//System.out.println("getchange");
if (newModel.getRssi()!=(oldModel.getRssi())) {
diff.putInt("price", newModel.getRssi());
}
if (diff.size() == 0) {
return null;
}
// }
return diff;
//return super.getChangePayload(oldItemPosition, newItemPosition);
}
}```
Activity Class:-
public class RepeaterAdvertise extends AppCompatActivity {
private static BluetoothAdapter mBluetoothAdapter;
private static BluetoothLeScanner mLEScanner;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
private static boolean mScanning;
private static Handler mHandler;
private static final long SCAN_TIMEOUT = 20000;
public DevData data;
public Button cc;
//List<BluetoothDevice> mBluetoothDevice;
RecyclerView recyclerView;
ReapeaterDeviceAdapter reapeaterDeviceAdapter;
ArrayList<RepeaterModel> modelArrayList;// = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repeater_advertise);
modelArrayList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.devdata);
//dummyData();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
reapeaterDeviceAdapter = new ReapeaterDeviceAdapter(RepeaterAdvertise.this, modelArrayList);
recyclerView.setAdapter(reapeaterDeviceAdapter);
mHandler = new Handler();
final Intent intent = getIntent();
data = (DevData) intent.getSerializableExtra(SINGLE_DEV_DATA);
}
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false,data.getMac_address());
}
#Override
protected void onResume() {
super.onResume();
scanLeDevice(true,data.getMac_address());
}
private void scanLeDevice(final boolean enable,String mac) {
if (enable) { // enable set to start scanning
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if(mScanning) {
mScanning = false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//noinspection deprecation
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
invalidateOptionsMenu();
}
}
}, SCAN_TIMEOUT);
mScanning = true;
UUID[] motorServiceArray = {PSoCBleRobotService.getMotorServiceUUID()};
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//noinspection deprecation
mBluetoothAdapter.startLeScan(motorServiceArray, mLeScanCallback);
} else { // New BLE scanning introduced in LOLLIPOP
ScanSettings settings;
List<ScanFilter> filters;
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<>();
//ScanFilter filter = new ScanFilter.Builder().setServiceUuid(PUuid).build();
//ScanFilter filter = new ScanFilter.Builder().setManufacturerData(89,new byte[] {}).build();
ScanFilter filter = new ScanFilter.Builder().setDeviceAddress(mac).build();
filters.add(filter);
if(mLEScanner==null)
{
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else { // enable set to stop scanning
if(mScanning) {
mScanning = false;
if (Build.VERSION.SDK_INT < 21) {
//noinspection deprecation
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
invalidateOptionsMenu();
}
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run()
{
byte[] haha = scanRecord;
/* if(!mBluetoothDevice.contains(device))
{
//only add new devices
mBluetoothDevice.add(device);
mBleName.add(device.getName());
mBleArrayAdapter.notifyDataSetChanged(); // Update the list on the screen
}*/
}
});
}
};
public static String SbytesToHex(SparseArray<byte[]> bytes) {
StringBuilder builder = new StringBuilder();
byte[] dd = bytes.valueAt(0);
for (byte b: dd)
{
builder.append(String.format("%02x", b));
}
//System.out.println( dd.length);
return builder.toString();
}
public final ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
ScanRecord scanRecord = result.getScanRecord();
// mBluetoothDevice.add(result.getDevice());
SparseArray<byte[]> dataw = scanRecord.getManufacturerSpecificData();
if (dataw.size() > 0) {
//populate_devData(SbytesToHex(dataw));
String data = SbytesToHex(dataw);
ArrayList<RepeaterModel> repeaterModels= new ArrayList<>();
int rssi = Integer.valueOf(data.substring(12, 14), 16) - 256;
repeaterModels.add(new RepeaterModel(data.substring(0, 12), rssi, 1));
insert(repeaterModels);
} else if (false) {
//alertDialog.dismiss();
final Intent intent = new Intent(RepeaterAdvertise.this, ConfigurationView.class);
intent.putExtra(EXTRAS_BLE_ADDRESS, data.getMac_address());
intent.putExtra(EXTRAS_BLE_NAME, data.getName());
intent.putExtra(SINGLE_DEV_DATA, data.getDev_data());
scanLeDevice(false, data.getMac_address());
//mconfig=false;
startActivity(intent);
}
}
};
public void insert(ArrayList<RepeaterModel> rr)
{
modelArrayList.addAll(rr);
reapeaterDeviceAdapter.setData(rr);
}
}
add this line in insert function reapeaterDeviceAdapter.notifyDataSetChanged();
public void insert(ArrayList<RepeaterModel> rr){
modelArrayList.addAll(rr);
reapeaterDeviceAdapter.setData(rr);
reapeaterDeviceAdapter.notifyDataSetChanged();
}

How to implement search filter properly on a Recycleview in Android

I have successfully populated my recycleview from mysql database and I want to implement search filter on it. I have seen some examples and tried to implement it. I know i'm close but cant get it properly to work.
My current progress is when I try to search something the whole recycle view goes blank and nothing happens after that.
Here are my java code:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getHotelDetails();
mylearningAdapters1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.reviews_list);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
inputSearch = (EditText)findViewById(R.id.searchBar);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// filter your list from your input
filter(s.toString());
//you can use runnable postDelayed like 500 ms to delay search text
}
});
}
void filter(String text){
List<MyHotelReviewAdapter> temp = new ArrayList();
for(MyHotelReviewAdapter d: mylearningAdapters){
//or use .equal(text) with you want equal match
//use .toLowerCase() for better matches
if(d.getHotel_user().contains(text)){
temp.add(d);
}
}
//update recyclerview
RecyclerViewMyHotelReviewAdapter rc = new RecyclerViewMyHotelReviewAdapter(mylearningAdapters);
rc.updateList(temp);
}
Here is my Recycleview adapter class code:
RecyclerViewMyHotelReviewAdapter.java
public class RecyclerViewMyHotelReviewAdapter extends RecyclerView.Adapter<RecyclerViewMyHotelReviewAdapter.LearningHolder> {
static Context context;
public static List<MyHotelReviewAdapter> mylearningAdapters;
public RecyclerViewMyHotelReviewAdapter(List<MyHotelReviewAdapter> mylearningAdapters, Context context){
super();
this.mylearningAdapters = mylearningAdapters;
this.context = context;
}
public RecyclerViewMyHotelReviewAdapter(List<MyHotelReviewAdapter> mylearningAdapters) {
}
#Override
public RecyclerViewMyHotelReviewAdapter.LearningHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_hotel_details, parent, false);
LearningHolder learningHolder = new LearningHolder(view);
//RecyclerViewModuleAdapter.ModuleHolder moduleHolder = new RecyclerViewModuleAdapter.ModuleHolder(view);
return learningHolder;
}
#SuppressLint("NewApi")
#Override
public void onBindViewHolder(RecyclerViewMyHotelReviewAdapter.LearningHolder holder, int position) {
final MyHotelReviewAdapter mylearningAdapter1 = mylearningAdapters.get(position);
int t = 4;
String a = mylearningAdapter1.getHotel_People();
int c = t + Integer.parseInt(a);
//Toast.makeText(context, ""+c, Toast.LENGTH_SHORT).show();
holder.hotel_user.setText(mylearningAdapter1.getHotel_user());
holder.hotel_dateIn.setText(mylearningAdapter1.getHotel_CheckIn());
holder.hotel_dateOut.setText(mylearningAdapter1.getHotel_CheckOut());
holder.total.setText(String.valueOf("Guests: "+c));
holder.htlName.setText(mylearningAdapter1.getHotel_name());
holder.id.setText(mylearningAdapter1.getHotel_id());
//holder.english_d.setText(mylearningAdapter1.getEnglish());
}
public void updateList(List<MyHotelReviewAdapter> list){
mylearningAdapters = list;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mylearningAdapters.size();
}
public class LearningHolder extends RecyclerView.ViewHolder {
String deleteBooking = "http://site2test.in/OxygenClub/mobileapp/delete_booking_careTaker.php";
AppCompatTextView hotel_user, hotel_dateIn, hotel_dateOut, htlName, total, id;
Button checkIn, checkOut;
public LearningHolder(View itemView) {
super(itemView);
hotel_user = (AppCompatTextView)itemView.findViewById(R.id.name);
hotel_dateIn = (AppCompatTextView)itemView.findViewById(R.id.checkin);
hotel_dateOut = (AppCompatTextView)itemView.findViewById(R.id.checkout);
htlName = (AppCompatTextView)itemView.findViewById(R.id.hotelName);
total = (AppCompatTextView)itemView.findViewById(R.id.totalPeople);
id = (AppCompatTextView)itemView.findViewById(R.id.hotelId);
}
}
}...
My DataHolder class.
public class MyHotelReviewAdapter {
public String Hotel_People;
public String Hotel_CheckIn;
public String Hotel_CheckOut;
public String Hotel_User;
public String Hotel_Name;
public String Hotel_Id;
public String getHotel_CheckIn() {
return this.Hotel_CheckIn;
}
public void setHotel_CheckIn(String hotel_checkIn) {
this.Hotel_CheckIn = hotel_checkIn;
}
public String getHotel_CheckOut() {
return this.Hotel_CheckOut;
}
public void setHotel_CheckOut(String hotel_checkOut) {
this.Hotel_CheckOut = hotel_checkOut;
}
public String getHotel_People() {
return this.Hotel_People;
}
public void setHotel_People(String hotel_people) {
this.Hotel_People = hotel_people;
}
public String getHotel_user() {
return this.Hotel_User;
}
public void setHotel_user(String hotel_user) {
this.Hotel_User = hotel_user;
}
public String getHotel_name(){
return this.Hotel_Name;
}
public void setHotel_name(String hotel_name){
this.Hotel_Name = hotel_name;
}
public String getHotel_id(){
return this.Hotel_Id;
}
public void setHotel_id(String hotel_id){
this.Hotel_Id = hotel_id;
}
}
I want to search my data by Hotel_user. I have coded the value of getHotel_user in filter function.

Adding Arraylist to custom object not updating values in android

In the below android activity, trying to display data in a view pager and it is working as expected.
But in loadItemsForSuppliers method, when i am adding SupplierAndItemList object to it's arraylist, value returned from getInventoriesByItemDetails method is not updating properly rather takes last value always.
Can some body assist me what's wrong here ?
public class ScreenSlidePagerActivity extends BaseActivity {
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private Dealer dealerObject;
private ArrayList<ItemDetail> itemDetails;
private List<Dealer> supplierList;
private ArrayList<SupplierAndItemList> supplierAndItemLists = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
dealerObject = getIntent().getParcelableExtra(UiConstants.DEALER_OBJECT);
itemDetails = getIntent().getParcelableArrayListExtra("itemDetails");
supplierList = dealerObject.getParentSalesPoints(this,dealerObject.getServerId());
loadItemsForSuppliers();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(),supplierAndItemLists);
mPager.setAdapter(mPagerAdapter);
}
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id);
}
return inventories;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<SupplierAndItemList> supplierAndItemList;
public ScreenSlidePagerAdapter(FragmentManager fm, ArrayList<SupplierAndItemList> supplierAndItemList) {
super(fm);
this.supplierAndItemList = supplierAndItemList;
}
#Override
public Fragment getItem(int position) {
SupplierAndItemList supplierAndItems = supplierAndItemList.get(position);
ScreenSlidePageFragment f = new ScreenSlidePageFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("supplierAndItems",supplierAndItems.getSelectedItemList());
bundle.putString("supplierName",supplierAndItems.getDealerName());
f.setArguments(bundle);
return f;
}
#Override
public int getCount() {
return supplierAndItemList.size();
}
}
}
SupplierAndItemList class
public class SupplierAndItemList implements Parcelable {
public String dealerName;
public ArrayList<ItemDetail> selectedItemList;
public SupplierAndItemList() {
selectedItemList = new ArrayList<>();
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public ArrayList<ItemDetail> getSelectedItemList() {
return selectedItemList;
}
public void setSelectedItemList(ArrayList<ItemDetail> itemList) {
this.selectedItemList = itemList;
}
protected SupplierAndItemList(Parcel in) {
dealerName = in.readString();
selectedItemList = in.readArrayList(ItemDetail.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dealerName);
dest.writeList(selectedItemList);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<SupplierAndItemList> CREATOR = new Parcelable.Creator<SupplierAndItemList>() {
#Override
public SupplierAndItemList createFromParcel(Parcel in) {
return new SupplierAndItemList(in);
}
#Override
public SupplierAndItemList[] newArray(int size) {
return new SupplierAndItemList[size];
}
};
}
ItemDetail class
public class ItemDetail implements Parcelable {
public int itemId;
public String itemName;
public String salesPointLastStock;
public String salesPointLastStockTakingDate;
public String parentSalesPointLastStock;
public String parentSalesPointLastStockTakingDate;
public IDStockInput idStockInput;
public IDReturnInput idReturnInput;
public IDOrderInput idOrderInput;
public boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setIsSelected(boolean isUpdated) {
this.isSelected = isUpdated;
}
public String getParentSalesPointLastStockTakingDate() {
return parentSalesPointLastStockTakingDate;
}
public void setParentSalesPointLastStockTakingDate(String parentSalesPointLastStockTakingDate) {
this.parentSalesPointLastStockTakingDate = parentSalesPointLastStockTakingDate;
}
public String getParentSalesPointLastStock() {
return parentSalesPointLastStock;
}
public void setParentSalesPointLastStock(String parentSalesPointLastStock) {
this.parentSalesPointLastStock = parentSalesPointLastStock;
}
#NonNull
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
#NonNull
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
#NonNull
public String getSalesPointLastStock() {
return salesPointLastStock;
}
public void setSalesPointLastStock(String salesPointLastStock) {
this.salesPointLastStock = salesPointLastStock;
}
#NonNull
public String getSalesPointLastStockTakingDate() {
return salesPointLastStockTakingDate;
}
public void setSalesPointLastStockTakingDate(String salesPointLastStockTakingDate) {
this.salesPointLastStockTakingDate = salesPointLastStockTakingDate;
}
public IDStockInput getIdStockInput() {
return idStockInput;
}
public void setIdStockInput(IDStockInput idStockInput) {
this.idStockInput = idStockInput;
}
public IDReturnInput getIdReturnInput() {
return idReturnInput;
}
public void setIdReturnInput(IDReturnInput idReturnInput) {
this.idReturnInput = idReturnInput;
}
public IDOrderInput getIdOrderInput() {
return idOrderInput;
}
public void setIdOrderInput(IDOrderInput idOrderInput) {
this.idOrderInput = idOrderInput;
}
public ItemDetail() {
idStockInput = new IDStockInput();
idReturnInput = new IDReturnInput();
idOrderInput = new IDOrderInput();
}
protected ItemDetail(Parcel in) {
itemId = in.readInt();
itemName = in.readString();
salesPointLastStock = in.readString();
salesPointLastStockTakingDate = in.readString();
parentSalesPointLastStock = in.readString();
parentSalesPointLastStockTakingDate = in.readString();
isSelected =in.readInt()==1;
idStockInput = (IDStockInput) in.readValue(IDStockInput.class.getClassLoader());
idReturnInput = (IDReturnInput) in.readValue(IDReturnInput.class.getClassLoader());
idOrderInput = (IDOrderInput) in.readValue(IDOrderInput.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(itemId);
dest.writeString(itemName);
dest.writeString(salesPointLastStock);
dest.writeString(salesPointLastStockTakingDate);
dest.writeString(parentSalesPointLastStock);
dest.writeString(parentSalesPointLastStockTakingDate);
dest.writeInt(isSelected ? 1 : 0);
dest.writeValue(idStockInput);
dest.writeValue(idReturnInput);
dest.writeValue(idOrderInput);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<ItemDetail> CREATOR = new Parcelable.Creator<ItemDetail>() {
#Override
public ItemDetail createFromParcel(Parcel in) {
return new ItemDetail(in);
}
#Override
public ItemDetail[] newArray(int size) {
return new ItemDetail[size];
}
};
}
I have go through your method I have found some assigning value issue
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id); // do this
}
return inventories; // you are not assigning value anywhere;
}
You are not assigning value to the inventories in getInventoriesByItemDetails. I think you should add item through inventories.add(id);
Check it , Hope this help
Set
mPager.setOffscreenPageLimit(1);

Categories