Get value from recycler view Adapter to activity - android

I have the layout as below. And I want to get all the data from the "quantity view" (from textview between "+" and "-" button) to my activity after the "proceed" button click.
I tried few of the answers but could not get the expected result. Can I get Some Help.
I have added a interface on adapter...
public interface OnItemClickListener {
void onItemClick(String id, String amount);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
and on the quantity change of the "quantity view" i tried to get the data from the adapter to activity
holder.quantityView.setOnQuantityChangeListener(new QuantityView.OnQuantityChangeListener() {
#Override
public void onQuantityChanged(int oldQuantity, int newQuantity, boolean programmatically) {
if (listener != null) {
listener.onItemClick(pricingPOJO.getId(), newQuantity + "");
}
}
#Override
public void onLimitReached() {
}
});

Maintain a Map of selected position to values like:
Map<Integer, Integer> positionToValueMap = new HashMap<>();
Then in OnBindViewHolder do this:
get your value like:
yourValue = positionToValueMap.get(getAdapterPosition());
set your value like:
positionToValueMap.put(getAdapterPosition(), yourValue);
then create getter method for positionToValueMap in adapter class and call the getter from your fragment/activity.
You are all done.

Related

Change the background color of selected item in recyclerview

I have a recyclerview where i want to change the color of the selected item and re change it on unselected. I have used an string arraylist and an interface for that here is interface code in adapter -
public interface Callback{
void onItemClicked(String i_name, boolean longClick);
}
Here is onclick and onlongclick code-
#Override
public void onClick(View view) {
String[] tag = ((String) view.getTag()).split(":");
String i_name = tag[1];
Toast.makeText(context, ""+i_name, Toast.LENGTH_SHORT).show();
if(callback != null)
{
callback.onItemClicked(i_name,false);
}
}
#Override
public boolean onLongClick(View view) {
String[] tag = ((String) view.getTag()).split(":");
String i_name = tag[1];
if(callback != null)
{
callback.onItemClicked(i_name,false);
}
return false;
}
Here is the toggleselected code -
public void toggleSelected(String i_name)
{
final boolean newState = !selectedList.contains(i_name);
if(newState)
{
// i want to give background color to i_name
selectedList.add(i_name);
Toast.makeText(context, "selected list1- "+selectedList, Toast.LENGTH_SHORT).show();
}
else
{
selectedList.remove((String) i_name);
Toast.makeText(context, "selected list2- "+selectedList, Toast.LENGTH_SHORT).show();
}
notifyDataSetChanged();
}
here is onItemClicked code from fragment -
#Override
public void onItemClicked(String i_name, boolean longClick) {
if(longClick)
{
((MyCategoryAdaptercheckbox) MyAdapter).toggleSelected(i_name);
}
else
{
((MyCategoryAdaptercheckbox) MyAdapter).toggleSelected(i_name);
}
}
This is the code from onbindviewholder where i am settingthe tag -
getMyCategoryAdapter1 = category_name.get(i);
viewHolder.view.setActivated(selectedList.contains(i));
viewHolder.view.setTag("items:" + getMyCategoryAdapter1.getC_name());
viewHolder.view.setOnClickListener(this);
viewHolder.view.setOnLongClickListener(this);
I want to give background color to i_name on toggleselected() method.HOw can i do this.Please help.Thanks in advance.
Basic idea for selecting and disselecting items in a recyclerview.
Maintain a tag in your model for selected and unselected.
for e.x
boolean isSelected;
when you populate the data make all values in your list for isSelected false bydefault.
Then in your long press set the value of isSelected to true for that position only in your arraylist and call notifyDataSetChanged.
and in your onbindviewholder check
if(yourModel.isSelected){
// show the row selected
}else {
// show the row unselected
}
I hope you get the idea.

How to set default value for spinner in android

In my application I want use Spinner and for this a use this library : enter link description here
I get array list from server with this code :
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<StringListDataResponse> call = api.getGetAggregationGenres();
call.enqueue(new Callback<StringListDataResponse>() {
#Override
public void onResponse(Call<StringListDataResponse> call, Response<StringListDataResponse> response) {
if (response.body().getData() != null) {
spinner.setItems(response.body().getData());
}
}
#Override
public void onFailure(Call<StringListDataResponse> call, Throwable t) {
}
});
Spinner selected Item code:
spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
#Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
}
});
but I want set default value for this spinner.
First show my default value, when selected item show this item from list.
how can I it?
Use this
spinner.setSelection(position);//to set default values
To get selected value use this
spinner.getSelectedItem();
Hi in your library you can use this
spinner.setSelectedIndex(2);

how to reload listview from another activity (adapter) class

i have tried all the things but i cant get proper result,i also try
adapter.clearAll()
adapter.notifyDataSetChanged()
but i cant get result when i delete row from list view its deleted from its position but when i change value of another row than the delete process working perfectly but changed value not set.getting value from database perfectly.
Here is my code please help me and tell where i m doing wrong.
Thank you in advance
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Identifier_fev = null;
String Default_Option = null;
String Quantity1 = null;
jffDatabase.open();
Cursor identifie = jffDatabase.getALL();
if (identifie.moveToPosition(position)) {
Identifier_fev = identifie.getString(identifie.getColumnIndexOrThrow("identifier"));
Default_Option = identifie.getString(identifie.getColumnIndexOrThrow("default_option"));
}
jffDatabase.delete(Identifier_fev, Default_Option);
identifier.remove(position);
title.remove(position);
defaultPrice.remove(position);
default_option.remove(position);
price.remove(position);
quantity.remove(position);
Cursor c1 = jffDatabase.getALL();
if (c1.moveToFirst()) {
do {
Quantity1 = c1.getString(c1.getColumnIndexOrThrow("quantity"));
update_quantity.add(Quantity1);
} while (c1.moveToNext());
}
for (int i = 0; i < update_quantity.size(); i++) {
Toast.makeText(ctx, "" + update_quantity, Toast.LENGTH_LONG).show();
Quantitylbl.setText(update_quantity.get(i).toString());
Toast.makeText(ctx, "set " + Quantitylbl.getText().toString(), Toast.LENGTH_LONG).show();
}
Quantity();
notifyDataSetChanged()
AddtoCartActivity.Cartcount.setText(String.valueOf(sum));
}
});
Good practice is use Interface
Create new Interface
public interface MyCustomObjectListener {
public void RefreshList();
//add parameter for delete if required ex-
//public void RefreshList(String Item_id);
}
then implement Activity by this Interface
YourActivityName extends Activity implements MyCustomObjectListener
And Implement Method
#Override
public void RefreshList() {
// Do your delete task and clear current List and get updated list task here
}
and from Base adapter onClick you can call method RefreshList like this
((YourActivityName)mContext).RefreshList();
you can delete and refresh list from #Override RefreshList

Custom Listener on Button click in ListView Item

I have created a Custom Listener interface for Button click in Adapter class, i followed this tutorial: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
Adapter:
holder.btnQtyIncrease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position);
}
cart = cartArrayList.get(position);
holder.textViewQuantity.setTag(cart);
if(cart.getQuantity() == 9) {
Toast.makeText(context, "Already reached", Toast.LENGTH_LONG).show();
return ;
}
else
{
cart.setQuantity(cart.getQuantity() + 1);
holder.textViewQuantity.setText(String.valueOf(cart.getQuantity()));
totalPrice = cart.getQuantity() * cart.getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
holder.textViewTotal.setText(cart.getTotal());
}
}
});
.....
return convertView;
}
And I have implemented Listener in Activity like this:
public class CartActivity extends Activity implements customButtonListener {
......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("CartActivity-onCreate", "onCreate");
setContentView(R.layout.activity_cart);
......
}
#Override
public void onResume()
{
super.onResume();
Log.d("CartActivity-onResume", "onResume");
}
#Override
public void onButtonClickListner(int position) {
totalPrice = CartArrayList.cartArraylist.get(position).getQuantity() * CartArrayList.cartArraylist.get(position).getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
subTotal = subTotal + totalPrice;
}
}
As you can see inside for loop i am setting and getting total of each and every list item, and then calculating subTotal of ArrayList items...
But whenever i do tap on btnQtyIncrease it makes change in total of list item price, but it would not effect on subTotal amount
You should change you logic in some way that it calculates the subTotal in adapter only and then just pass the final value to interface which will simply set it in then textview
So your code should look like:
holder.btnQtyIncrease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cart = cartArrayList.get(position);
holder.textViewQuantity.setTag(cart);
if(cart.getQuantity() == 9) {
Toast.makeText(context, "Already reached", Toast.LENGTH_LONG).show();
return ;
}
else
{
cart.setQuantity(cart.getQuantity() + 1);
holder.textViewQuantity.setText(String.valueOf(cart.getQuantity()));
totalPrice = cart.getQuantity() * cart.getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
holder.textViewTotal.setText(cart.getTotal());
}
}
// calculate total here
if (customListner != null) {
customListner.onButtonClickListner(getTotalValue());
}
});
Define a method getTotalValue in adapter which will iterate through the array and find the subTotal value.
And then simply set it in the textView
#Override
public void onButtonClickListner(float subTotal ) {
txtView.setText(String.valueOf(subTotal));
}
Accordingly, change the interface signature as :
public void onButtonClickListner(float total);
How to update value in Activity when do change in Adapter class
To update data in Activity on btnQtyIncrease Button click. create custom event listener using interface which will trigger in Activity when any change made in Quantity.
See following example for creating custom Listener :
How to create our own Listener interface in android?

Checkboxes not changing checked status in UI?

I have a ListView that I am trying to use with a checkable item list. I am calling the toggle() method on my list item class in the ArrayAdaptor, but the checkbox is not being ticked in the UI. However, I can confirm that the correct items are being selected in the UI, and that the "isChecked()" status reports back correctly--just the UI doesn't change at all. Are there any special methods I need to call to update the checkbox graphic for the UI?
To put it another way--how do I programmatically tell the UI that a checkbox should show up as "checked"? It seems this should be a very simple process, but I've been having a lot of trouble finding this information.
Code is as follows:
For the item data class in the ArrayAdaptor:
public class SelectedItemData extends CheckedTextView {
public String _item_name;
public String getItemName()
{
return _item_name;
}
public void setItemName(String in_name)
{
_item_name = in_name;
}
// methods
public SelectedItemData(Context context) {
super(context);
init();
}
public void init()
{
this._item_name = "UNSET";
this.setChecked(false);
}
#Override
public String toString()
{
return _item_name;
}
}
In the Activity class (located within the onCreate method):
_selectedItemsListView = (ListView) findViewById(R.id.selected_items_listview);
_selectedItemsListView.setItemsCanFocus(false);
_selectedItemsListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
_selectedItemsListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View view, int position, long id) {
#SuppressWarnings("unchecked")
ArrayAdapter<SelectedItemData> itemsAdapter = (ArrayAdapter<SelectedItemData>)_selectedItemsListView.getAdapter();
SelectedItemData selectedItem = itemsAdapter.getItem(position);
selectedItem.toggle();
Toast.makeText(view.getContext(), "Item " + selectedItem.getItemName() + " Selected!", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Is Item Checked? " + selectedItem.isChecked());
_selectedItemsListView.setAdapter(itemsAdapter);
}
});
Any guidance on how to enable the UI to properly display that one of the items have been selected/checked would be great. Thanks!
You have to update your adapter with the new item and set it to the listview. (itemsAdapter.setItem(item,position))

Categories

Resources