I'm working on an android application where I have to use custom listview with checkboxes. When user checks/unchecks, I need to add/remove objects in array list respectively.
here is my code:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selectedView=view;
System.out.println("Position of list item:"+position);
if(parent.getAdapter().equals(categoryAdapter))
{
System.out.println("First Adapter");
fl=new FoodList();
System.out.println("Tag:"+view.getTag());
btOrder.setVisibility(View.GONE);
addToOrder.setVisibility(View.VISIBLE);
back.setVisibility(View.VISIBLE);
buttonSeperator.setVisibility(View.VISIBLE);
fl.bundleCategory=fc.list[position];
fl.foodListService();
checks=new SparseBooleanArray();
quantity=new SparseArray<Integer>();
orderList=new ArrayList<Order>();
order=new Order();
Order Null=null;
for(int i=0;i<fl.foodList.size();i++)
{
checks.put(i, false);
quantity.put(i, 0);
order.setQuantity(0);
order.setItem("");
//orderList.add(i,Null);
//orderList.add(i,order);
orderList.add(order);
System.out.println("Adding at pos:"+i+"Value:"+Null);
}
WaiterFoodAdapter foodAdapter=new WaiterFoodAdapter(this, R.layout.take_order_list, fl.foodList);
categoryList.setAdapter(foodAdapter);
categoryList.setOnItemClickListener(this);
}
else
{
System.out.println("Second Adapter:Id="+parent.getId());
if(view != null)
{
final TextView tvItem=(TextView)selectedView.findViewById(R.id.foodName);
final TextView tvQuantity=(TextView)selectedView.findViewById(R.id.quantity);
selectedPosition=position;
SelectFood = (CheckBox)view.findViewById(R.id.selectFood);
if(SelectFood.isChecked())
{
SelectFood.setChecked(false);
checks.put(selectedPosition, false);
quantity.put(selectedPosition,0);
//order.setQuantity(0);
//order.setItem("");
System.out.println("Removing at pos:"+selectedPosition+"Value:"+orderList.get(selectedPosition).getItem()+orderList.get(selectedPosition).getQuantity());
orderList.remove(orderList.get(selectedPosition));
tvQuantity.setText("0");
System.out.println("Position="+selectedPosition);
}
else
{
SelectFood.setChecked(true);
checks.put(selectedPosition, true);
System.out.println("Position="+selectedPosition);
//orderList=new ArrayList<Order>();
final AlertDialog.Builder quantityAlert= new AlertDialog.Builder(TakeOrder.this);
quantityAlert.setTitle("Quantity");
quantityAlert.setMessage("Please enter quantity");
final EditText input = new EditText(TakeOrder.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
quantityAlert.setView(input);
quantityAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
value = input.getText();
if(value.toString().equals(""))
{
SelectFood.setChecked(false);
Toast msg=Toast.makeText(TakeOrder.this, "Please provide quantity", Toast.LENGTH_SHORT);
msg.show();
}
else
if(value.toString().equals("0"))
{
SelectFood.setChecked(false);
Toast msg=Toast.makeText(TakeOrder.this, "Please enter valid quantity", Toast.LENGTH_SHORT);
msg.show();
}
else
{
tvQuantity.setText(value);
quantity.put(selectedPosition, Integer.valueOf(value.toString()));
order.setQuantity(Integer.valueOf(tvQuantity.getText().toString()));
order.setItem(tvItem.getText().toString());
orderList.add(selectedPosition, order);
System.out.println("setting at pos:"+selectedPosition+"Value:"+orderList.get(selectedPosition).getItem()+orderList.get(selectedPosition).getQuantity());
}
//Log.v("Item:",orderList.get(selectedPosition).getItem());
//Log.v("Quantity:",String.valueOf(orderList.get(selectedPosition).getQuantity()));
}
});
quantityAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
SelectFood.setChecked(false);
}
});
quantityAlert.show();
}
}
}
}
When user click addToOrder button it just search for checked checkboxes and gettin relevant textViews values of checked listItems..
public void addToOrder(View v)
{
for(int i=0;i<fl.foodList.size();i++)
{
if(checks.get(i)==true)
{
System.out.println("Order is:"+orderList.get(i).getItem()+orderList.get(i).getQuantity());
}
}
}
this is my adapter which is just for custom view purpose
public class WaiterFoodAdapter extends ArrayAdapter<Food>
{
Context context;
TakeOrder holder;
int layoutResourceId;
List<Food> foodList;
public WaiterFoodAdapter(Context context, int layoutResourceId,List<Food> foodList)
{
super(context, layoutResourceId, foodList);
this.context=context;
this.layoutResourceId=layoutResourceId;
this.foodList=foodList;
}
#Override
public View getView(int position,View convertView,ViewGroup parent)
{
View row=convertView;
if(row==null)
{
LayoutInflater inflater=((Activity)context).getLayoutInflater();
row=inflater.inflate(layoutResourceId, parent,false);
holder=new TakeOrder();
holder.foodIcon=(ImageView)row.findViewById(R.id.foodIcon);
holder.tvFoodName=(TextView)row.findViewById(R.id.foodName);
holder.cbSelectFood=(CheckBox)row.findViewById(R.id.selectFood);
holder.cbSelectFood.setClickable(false);
holder.tvFoodDescription=(TextView)row.findViewById(R.id.foodDescription);
holder.tvFoodQuantity=(TextView)row.findViewById(R.id.foodQuantity);
holder.tvQuantity=(TextView)row.findViewById(R.id.quantity);
row.setTag(holder);
}
else
{
holder=(TakeOrder)row.getTag();
}
if(fl.bundleCategory.equals("Appetisers"))
{
holder.foodIcon.setImageResource(R.drawable.appetiser);
}
else
if(fl.bundleCategory.equals("Main Courses"))
{
holder.foodIcon.setImageResource(R.drawable.main_course);
}
else
if(fl.bundleCategory.equals("Sides"))
{
holder.foodIcon.setImageResource(R.drawable.sides);
}
else
if(fl.bundleCategory.equals("Desserts"))
{
holder.foodIcon.setImageResource(R.drawable.desserts);
}
else
if(fl.bundleCategory.equals("Drinks"))
{
holder.foodIcon.setImageResource(R.drawable.drinks);
}
holder.tvFoodName.setText(foodList.get(position).getMenuItem());
holder.tvFoodDescription.setText(foodList.get(position).getDescription());
holder.cbSelectFood.setChecked(checks.get(position));
holder.tvQuantity.setText(String.valueOf(quantity.get(position)));
return row;
}
}
Suppose i select(check) two list items and then press addToOrder button it just prints the last seleccted item twice. I dont know why its just overridding a first object in my List
I think my logic is correct, but dont know why its not working??
Can any one please help
You should make a method in your adapter which lets your update the current arraylist or add/remove the item you pass. But I can't see how you implemented your adapter which probably is the most important code...
You need something like this, inside your adapter (this is to update a full list):
public void updateListArray(ArrayList<Item> list) {
this.clear();
for(Item item : list) {
this.add(item);
}
notifyDataSetChanged();
}
Related
There is Scroll by loading RecyclerView(Lazy loading). When an item quantity is incremented by adding the plus button to say 10. after loading the next set of items while scrolling, The item quantity(10) is reset to 1 and 10 will be displayed for another item.
In the same sequence, if the unit is changed(by the spinner) to another unit the corresponding image will be loaded but after scrolling the unit and image will change back to initial unit.
When the image of an item is clicked, a dialog will show the details of the selected item . Sometimes the image in the dialog is correct but image of the RecyclerView is incorrect, will take time to load or will not load.
public class ArticleRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements Filterable {
private static final String TAG = "ArticleAdapter";
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private Context context;
private Dialog articleDescriptionDialog;
private UOMOffersLIistViewAdapter uomOffersLIistViewAdapter;
private List<ArticleDetails> articleDetailsList;
private HomeActivityViewModel homeActivityViewModel;
private ItemFilter itemFilter = new ItemFilter();
private GetViewListener getViewListener;
private int lastPosition = -1;
private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
/*
* isLoading - to set the remote loading and complete status to fix back to back load more call
* isMoreDataAvailable - to set whether more data from server available or not.
* It will prevent useless load more request even after all the server data loaded
* */
public ArticleRecyclerViewAdapter(Context context, List<ArticleDetails> articleDetailsList
, HomeActivityViewModel homeActivityViewModel, Fragment fragment) {
this.context = context;
this.articleDetailsList = articleDetailsList;
this.homeActivityViewModel = homeActivityViewModel;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
if (viewType == VIEW_TYPE_ITEM) {
return new ItemViewHolder(inflater.inflate(R.layout.recycler_view_article_layout, parent, false));
} else {
return new LoadHolder(inflater.inflate(R.layout.item_loading_layout, parent, false));
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
if (position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true;
loadMoreListener.onLoadMore();
}
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
populateItemRows((ItemViewHolder) viewHolder, position);
}
//No else part needed as load holder doesn't bind any data
}
#Override
public int getItemViewType(int position) {
if (articleDetailsList.get(position).isLoading()) {
return VIEW_TYPE_LOADING;
} else {
return VIEW_TYPE_ITEM;
}
}
#Override
public int getItemCount() {
return articleDetailsList.size();
}
#Override
public long getItemId(int position) {
return position;
}
/* VIEW HOLDERS */
static class ItemViewHolder extends RecyclerView.ViewHolder {
private ImageView stockImageView, copyStockImageView;
private TextView articleNameTextView, articleStockAmountTextView, articleOfferTextView, addCartTextView;
private NumberPicker articleStockQuantityNumberPicker;
private Spinner articleStockSpinner;
private ImageButton offerInfoImageButton;
private int selectedStockItemPosition, stockQuantity;
private String articleStockQuantityString = "";
private Integer stockId;
private double stockAmount;
public ItemViewHolder(View itemView) {
super(itemView);
stockImageView = itemView.findViewById(R.id.stockImgv);
copyStockImageView = itemView.findViewById(R.id.copyStockImgv);//for fly to cart animation
articleNameTextView = itemView.findViewById(R.id.articleNameTxt);
articleStockAmountTextView = itemView.findViewById(R.id.stock_amount_txt);
articleOfferTextView = itemView.findViewById(R.id.offer_txt);
offerInfoImageButton = itemView.findViewById(R.id.offerInfo_imgbtn);
addCartTextView = itemView.findViewById(R.id.addCart_txt);
articleStockSpinner = itemView.findViewById(R.id.stock_spnr);
articleStockQuantityNumberPicker = itemView.findViewById(R.id.qty_numberPicker);
articleStockQuantityNumberPicker.setMin(1);
articleStockQuantityNumberPicker.setUnit(1);
// no limit.
// viewHolder.quantityNumberPicker.setMax(15);
}
}
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 articleRecyclerViewAdapter.notifyDataChanged(); after update the list
*/
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public interface OnLoadMoreListener {
void onLoadMore();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
private void populateItemRows(ItemViewHolder itemViewHolder, int itemPos) {
int itemPosition = itemViewHolder.getAdapterPosition();
try {
itemViewHolder.copyStockImageView.setImageResource(R.drawable.error_logo);//initialize with error logo.
itemViewHolder.stockImageView.setImageResource(R.drawable.error_logo);//initialize with error logo.
} catch (Exception e) {
e.printStackTrace();
}
itemViewHolder.articleNameTextView.setText(articleDetailsList.get(itemPosition).getArticleName());
itemViewHolder.articleNameTextView.setSelected(true);//for marquee
itemViewHolder.articleOfferTextView.setSelected(true);//for marquee
itemViewHolder.articleStockAmountTextView.setSelected(true);//for marquee
itemViewHolder.articleOfferTextView.setVisibility(View.GONE);//for demo (now no offer and schemes).
itemViewHolder.offerInfoImageButton.setVisibility(View.GONE);//for demo
setStockSpinner(itemViewHolder, itemPosition);
itemViewHolder.offerInfoImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//setUOMOffersDIalog(articleDetailsList.get(itemPosition));
}
});
itemViewHolder.articleStockQuantityNumberPicker.setValueChangedListener(new ValueChangedListener() {
#Override
public void valueChanged(int quantity, ActionEnum action) {
itemViewHolder.articleStockQuantityString = Integer.valueOf(quantity).toString();
}
});
itemViewHolder.addCartTextView.setOnClickListener(new SingleClickListener() {
#Override
public void onSingleClick(View v) {
itemViewHolder.articleStockQuantityString = Integer.valueOf(itemViewHolder.articleStockQuantityNumberPicker.getValue()).toString();
itemViewHolder.stockQuantity = Integer.valueOf(itemViewHolder.articleStockQuantityString);
itemViewHolder.stockAmount = articleDetailsList.get(itemPosition).getStockDetailsList()
.get(itemViewHolder.articleStockSpinner.getSelectedItemPosition()).getmRP();
itemViewHolder.stockId = articleDetailsList.get(itemPosition).getStockDetailsList()
.get(itemViewHolder.articleStockSpinner.getSelectedItemPosition()).getStockId();
Double stockDiscountAmount = 0.0;
//TODO: 26-Oct-19 discount hardcoded.
if (itemViewHolder.stockQuantity > 0) {
addItemToCart(itemViewHolder, itemViewHolder.stockId, itemViewHolder.stockQuantity, itemViewHolder.stockAmount, stockDiscountAmount);
} else {
//not using (used for when user enter invalid quantity)
MDToast.makeText(context, FinalVariables.ToastMessages.VALID_QUANTITY
, MDToast.LENGTH_SHORT, MDToast.TYPE_WARNING).show();
}
}
});
itemViewHolder.stockImageView.setOnClickListener(new SingleClickListener() {
#Override
public void onSingleClick(View v) {
itemViewHolder.articleOfferTextView.setVisibility(View.VISIBLE);
itemViewHolder.articleOfferTextView.setText( ""+ itemViewHolder.stockQuantity);
DialogUtils.showArticleDescription(context, articleDetailsList.get(itemPosition)
, itemViewHolder.selectedStockItemPosition, new DialogButtonClickListener() {
#Override
public void positiveButtonClick() {
//do nothing.
}
});
}
});
// Here you apply the animation when the view is bound
setAnimation(itemViewHolder.itemView, itemPosition);
}
private void setStockSpinner(ItemViewHolder itemViewHolder, int itemPosition) {
UOMSpinnerAdapter uomSpinnerAdapter = new UOMSpinnerAdapter(context, R.layout.spinner_uom_layout
, StringUtils.makeUomStringArrayForSpinner(articleDetailsList.get(itemPosition).getStockDetailsList()));
itemViewHolder.articleStockSpinner.setAdapter(uomSpinnerAdapter);
// Setting OnItemClickListener to the Spinner
itemViewHolder.articleStockSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
itemViewHolder.selectedStockItemPosition = position;
itemViewHolder.articleStockAmountTextView.setText(StringUtils.addAED(StringUtils.round3(
+articleDetailsList.get(itemPosition)
.getStockDetailsList().get(position).getmRP())));
//show image from link
try {
if (!articleDetailsList.get(itemPosition).getStockDetailsList().
get(position).getStockImageDetailsList().isEmpty()) {
ImageUtils.setGlide(context, itemViewHolder.stockImageView
, articleDetailsList.get(itemPosition).getStockDetailsList().
get(position).getStockImageDetailsList().get(0).getStockImage());
//same as stockImageView but used to animate fly to cart
ImageUtils.setGlide(context, itemViewHolder.copyStockImageView
, articleDetailsList.get(itemPosition).getStockDetailsList().
get(position).getStockImageDetailsList().get(0).getStockImage());
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
if (articleDetailsList.get(itemPosition).getStockDetailsList().size() > 0)
itemViewHolder.articleStockAmountTextView.setText(StringUtils.addAED(
StringUtils.round3(+articleDetailsList.get(itemPosition).getStockDetailsList().get(0).getmRP())));
itemViewHolder.selectedStockItemPosition = itemViewHolder.articleStockSpinner.getSelectedItemPosition();
}
});
}
private void addItemToCart(ItemViewHolder itemViewHolder, Integer stockId, Integer stockQuantity
, Double stockAmount, Double stockDiscountAmount) {
homeActivityViewModel.isItemAlreadyCarted(stockId
, new RetrieveDataListner() {
#Override
public void onDone(Object object) {
boolean isItemAlreadyCarted = (boolean) object;
if (!isItemAlreadyCarted) {//item not in cart,add to cart.
CartedItems cartedItem = new CartedItems();
cartedItem.setStockId(stockId);
cartedItem.setStockQuantity(stockQuantity);
cartedItem.setStockAmount(stockAmount);
cartedItem.setTotalAmount(CalcUtils.calculateTotalAmount(stockQuantity, stockAmount));
cartedItem.setNetAmount(CalcUtils.calculateNetAmount(stockQuantity
, stockAmount, stockDiscountAmount));
homeActivityViewModel.insertCartedItem(cartedItem
, new InsertDbSuccessListner() {
#Override
public void onSuccess() {
//set view to call back method for fly to cart animation
if (getViewListener != null){
getViewListener.onGetView(itemViewHolder.copyStockImageView);
}
itemViewHolder.articleStockQuantityNumberPicker.setValue(1);//reset item quantity in ui.
// TODO: 21-Mar-19 check fly to cart only in home activity or not
if (context instanceof MainActivity) {
MDToast.makeText(context, TextMessages.ITEM_ADDED
, MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS).show();
} else if (context instanceof HomeActivity) {
try {
((HomeActivity) context).setCartDetails();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure() {
}
});
} else {//item already carted,asking to add new quantity to carted quantity.
DialogUtils.showConformAlertDialog1(context, TextMessages.ITEM_ALREADY_CARTED
, TextMessages.ITEM_ALREADY_CARTED_WARNING
, StringValues.NO, StringValues.YES, new DialogButtonClickListener() {
#Override
public void positiveButtonClick() {//adding new quantity to existing quantity.
//set view to call back method for fly to cart animation
if (getViewListener != null)
getViewListener.onGetView(itemViewHolder.copyStockImageView);
homeActivityViewModel.updateCartedItemWithExistingValues(stockId, stockQuantity
, CalcUtils.calculateTotalAmount(stockQuantity, stockAmount),
CalcUtils.calculateNetAmount(stockQuantity, stockAmount, stockDiscountAmount)
, null);
itemViewHolder.articleStockQuantityNumberPicker.setValue(1);//reset item quantity in ui.
}
#Override
public void negativeButtonClick() {
}
});
}
}
});
}
/**
* Here is the key method to apply the animation
*/
private void setAnimation(View viewToAnimate, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(context, R.anim.fall_down);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
/**
* register listener for get article image(copyStockImageView)
* for fly to cart animation.
* the view get back to the call back(categorizedArticleFragment)).
*
* #param getViewListener
*/
public void setGetViewListener(GetViewListener getViewListener) {
this.getViewListener = getViewListener;
}
#Override
public Filter getFilter() {
return itemFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<ArticleDetails> list = articleDetailsList;
int count = list.size();
final List<ArticleDetails> nlist = new ArrayList<ArticleDetails>(count);
ArticleDetails filterableString;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.getArticleName().toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
articleDetailsList = (ArrayList<ArticleDetails>) results.values;
notifyDataSetChanged();
}
}
}
Fragments onCreate
#Override
public View onCreateView(#NonNull LayoutInflater layoutInflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
context = viewGroup.getContext();
parentView = layoutInflater.inflate(R.layout.fragment_article, viewGroup, false);
homeActivityViewModel = getViewModel();
articleRecyclerView = parentView.findViewById(R.id.subcategory_rcylv);
Bundle bundle = getArguments();
Integer offset = bundle.getInt(TagNames.OFFSET, 0);
Integer numberOfRows = bundle.getInt(TagNames.NUMBER_OF_ROWS, FinalVariables.GETTING_DATA_COUNT_FROM_API);
filterTypeId = bundle.getInt(TagNames.FILTER_TYPE_ID, FilterTypes.SUGGESTED);
String filterText = bundle.getString(TagNames.FILTER_TEXT, "");
Integer categoryId = bundle.getInt(TagNames.CATEGORY_ID, 0);
initArticleRecyclerViewAdapter(articleDetailsList, filterText, categoryId, offset, numberOfRows);
return parentView;
}
Initializing Adapter
private void initArticleRecyclerViewAdapter(List<ArticleDetails> articleDetailsList
, String filterText, Integer categoryId, int offset, int numberOfRows) {
articleRecyclerViewAdapter = new ArticleRecyclerViewAdapter(context, this.articleDetailsList, homeActivityViewModel, this);
articleRecyclerViewAdapter.setLoadMoreListener(new ArticleRecyclerViewAdapter.OnLoadMoreListener() {
#Override
public void onLoadMore() {
articleRecyclerView.post(new Runnable() {
#Override
public void run() {
int index = ArticleFragment.this.articleDetailsList.size();
loadMore(filterText, categoryId, index, numberOfRows);
Log.e(TAG, "scrolling,index: " + 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
}
});
articleRecyclerView.setHasFixedSize(true);
articleRecyclerView.setLayoutManager(new GridLayoutManager(context, 3));
articleRecyclerView.setAdapter(articleRecyclerViewAdapter);
load(filterText, categoryId, offset, numberOfRows);
}
Loading data
private void loadMore(String filterText, Integer categoryId, int offset, int numberOfRows) {
//add loading progress view
articleDetailsList.add(new ArticleDetails(true));
articleRecyclerViewAdapter.notifyItemInserted(articleDetailsList.size() - 1);
Integer storeId = FileUtils.getPreferenceInt(context
, Preferences.CUSTOMER_PREFERENCE, TagNames.STORE_ID);
Integer distributionChannelId = FileUtils.getPreferenceInt(context
, Preferences.CUSTOMER_PREFERENCE, TagNames.DISTRIBUTION_CHANNEL_ID);
homeActivityViewModel.getAllStockItemByCustomer(
DeviceUtils.getCredential(context, ServiceNames.GET_ALL_STOCK_ITEM_BY_CUSTOMER)
, storeId, distributionChannelId, filterTypeId, filterText, categoryId, offset, numberOfRows
, new ApiCallbackListener() {
#Override
public void onSuccess(Object object) {
try {
if (object != null) {
if (object instanceof GetAllStockItemByCustomerStatusReturn) {
//otp generation failed,
GetAllStockItemByCustomerStatusReturn getAllStockItemByCustomerStatusReturn
= (GetAllStockItemByCustomerStatusReturn) object;
showGetAllStockItemByCustomerErrorDialog(getAllStockItemByCustomerStatusReturn);
} else if (object instanceof List) {
List<GetAllStockItemByCustomerResponseData> getAllStockItemByCustomerResponseDataList
= (List<GetAllStockItemByCustomerResponseData>) object;
//remove loading view
articleDetailsList.remove(articleDetailsList.size() - 1);
List<ArticleDetails> result = new ArrayList<>();
result = homeActivityViewModel.getArticles(getAllStockItemByCustomerResponseDataList);
homeActivityViewModel.insertAllStockItemByCustomer(context,filterTypeId
, getAllStockItemByCustomerResponseDataList, null);
if (result.size() > 0) {
//add loaded data
articleDetailsList.addAll(result);
} else {//result size 0 means there is no more data available at server
articleRecyclerViewAdapter.setMoreDataAvailable(false);
//telling articleRecyclerViewAdapter to stop calling load more as no more server data available
//Toast.makeText(context, "No More Data Available", Toast.LENGTH_LONG).show();
}
articleRecyclerViewAdapter.notifyDataChanged();
//should call the custom method articleRecyclerViewAdapter.notifyDataChanged here to get the correct loading status
} else {
MDToast.makeText(context, FinalVariables.ToastMessages.SOMETHING_WENT_WRONG
, MDToast.LENGTH_SHORT, MDToast.TYPE_WARNING).show();
}
} else {
MDToast.makeText(context, FinalVariables.ToastMessages.SOMETHING_WENT_WRONG
, MDToast.LENGTH_SHORT, MDToast.TYPE_WARNING).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void load(String filterText, Integer categoryId, int offset, int numberOfRows) {
Integer storeId = FileUtils.getPreferenceInt(context
, Preferences.CUSTOMER_PREFERENCE, TagNames.STORE_ID);
Integer distributionChannelId = FileUtils.getPreferenceInt(context
, Preferences.CUSTOMER_PREFERENCE, TagNames.DISTRIBUTION_CHANNEL_ID);
homeActivityViewModel.getAllStockItemByCustomer(
DeviceUtils.getCredential(context, ServiceNames.GET_ALL_STOCK_ITEM_BY_CUSTOMER)
, storeId, distributionChannelId, filterTypeId, filterText, categoryId, offset, numberOfRows
, new ApiCallbackListener() {
#Override
public void onSuccess(Object object) {
try {
if (object != null) {
if (object instanceof GetAllStockItemByCustomerStatusReturn) {
GetAllStockItemByCustomerStatusReturn getAllStockItemByCustomerStatusReturn
= (GetAllStockItemByCustomerStatusReturn) object;
showGetAllStockItemByCustomerErrorDialog(getAllStockItemByCustomerStatusReturn);
} else if (object instanceof List) {
List<GetAllStockItemByCustomerResponseData> getAllStockItemByCustomerResponseDataList
= (List<GetAllStockItemByCustomerResponseData>) object;
if (!getAllStockItemByCustomerResponseDataList.isEmpty()) {
if (offset == 0 && getAllStockItemByCustomerResponseDataList.get(0)
.getCategoryID() == StatusCodes.INVALID_CODE
&& filterTypeId == FilterTypes.SUGGESTED) {
//shows all article from store (filter type 0) if no article is mapped in suggested.
filterTypeId = FilterTypes.ALL;
load(filterText, categoryId, offset, numberOfRows);
}
}
articleDetailsList.addAll(homeActivityViewModel.getArticles(getAllStockItemByCustomerResponseDataList));
homeActivityViewModel.insertAllStockItemByCustomer(context,filterTypeId
, getAllStockItemByCustomerResponseDataList, null);
articleRecyclerViewAdapter.notifyDataChanged();
} else {
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
I'm trying to make a laundry ordering application. I've made it to the order process, at the end of the order process, the user clicks the next button to checkout the ordered results, I have successfully made the checkout results, but what I made is still in one variable string. how to put the checkout results into an array variable so that I can post the results in the form of JSONArray?
HERE IS MY ORDER ACTIVITY CODE :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
listProduk.setAdapter(productAdapter);
listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
productAdapter.setCheckBox(position);
}
});
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
tvTotal.setText(String.valueOf(0));
radioReguler.isChecked();
regular = true;
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);
txtnamaProduk.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
AND HERE IS THE CODE OF THE RESULT :
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
in my code above, I still use the variable checkbox to accommodate all the results of the order chosen by the user. how to put all the result into array variable so i can post to server as a JSONArray? Please help me to solve this problem. because i'm still a beginner in android.
HERE IS MY ADAPTER CODE IF NEEDED :
public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;
public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
this.context = context;
this.productItems = items;
this.produk = produk;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
final ProductModel items = productItems.get(position);
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_produk, null, true);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
viewHolder.count = (TextView) view.findViewById(R.id.count_product);
viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
viewHolder.price = (TextView) view.findViewById(R.id.product_price);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.checkBox.setText(items.getProduct_name());
viewHolder.price.setText(items.getProduct_price());
viewHolder.count.setText(String.valueOf(items.getCountProduct()));
//fungsi untuk set posisi textview + dan -
viewHolder.increase.setTag(R.integer.btn_plus_view, view);
viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);
//fungsi untuk disable textview + dan - jika checkbox tidak di klik
viewHolder.decrease.setOnClickListener(null);
viewHolder.increase.setOnClickListener(null);
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
viewHolder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);
int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.tambah(pos);
}
});
viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);
int total = productItems.get(pos).getCountProduct();
if (total>0){
int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.kurang(pos);
}
}
});
} else {
viewHolder.checkBox.setChecked(false);
//fungsi untuk reset jumlah harga dan produk pada checkbox
String count = viewHolder.count.getText().toString();
int jumlah = Integer.parseInt(count);
int harga = Integer.parseInt(productItems.get(position).getProduct_price());
int kurang = jumlah * harga;
viewHolder.count.setText("0");
productItems.get(position).setCountProduct(0);
produk.kurangCheckbox(kurang);
}
return view;
}
public ArrayList<ProductModel> getAllData(){
return productItems;
}
public void setCheckBox(int position){
ProductModel items = productItems.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
static class ViewHolder{
TextView decrease, count, increase, price;
CheckBox checkBox;
}
}
just create getter setter method of Arraylist like below
CompleteOrder:-
public class CompleteOrder {
List<OrderItem> order_items;
public List<OrderItem> getOrder_items() {
return order_items;
}
public void setOrder_items(List<OrderItem> order_items) {
this.order_items = order_items;
}
}
Create another Getter setter class of variable you want to add in arraylist
OrderItem:-
public class OrderItem {
String product_name;
int product_total;
public OrderItem(String product_name, int product_total) {
this.product_name = product_name;
this.product_total = product_total;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_total() {
return product_total;
}
public void setProduct_total(int product_total) {
this.product_total = product_total;
}
}
Now in your onClick method just create new List as below
public void onClick(View view) {
String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
List<OrderItem> masterProductorderCount=new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);
}
}
completeOrder.setOrder_items(masterProductorderCount);
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(completeOrder);//pass object of CompleteOrder
}
});
CompleteOrder object give JSON output as below
{
"CompleteOrder":[
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
}
]
}
make a model that contains product name , total and etc,
then put each data into an object and put each object into an array
finally use Gson to map properties to model / list of models or the other way around.
ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
Model model = new Model();
model.productName = hold.getProduct_name();
model.total = total;
list.add(model);
}
}
String jsonArray = Gson().toJson(list);
You need to create a JSONObject for each entry in the JSONArray.
As far as I can see this should take care of it:
public void onClick(View view) {
String checkbox = "";
JSONArray jsonArray = new JSONArray();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
JSONObject jsonObj = new JSONObject();
jsonObj.put("product_name", hold.getProduct_name());
jsonObj.put("product_total", total);
jsonArray.put(jsonObj);
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
String jsonArrayString = jsonArray.toString();
formSubmit(dipilih);
}
Depending on your data the resulting string from jsonArrayString would be:
{[
{"product_name":"product1","product_total":1},
{"product_name":"product2","product_total":2},
{"product_name":"product3","product_total":3}
]}
I really do not know what you intend on doing with the JSON data so I just created a String "jsonArrayString".. do what ever you need to with it.
I am in the process of changing someone else's code from listView to recyclerView, changing code in my activity and my adapter where required - the adapter is a big change, with OnCreateView, onBindViewHolder and so on...
As the question indicates, category, name, phone, address, comment, public_or_private are posting successfully to mySql db, but nothing for checkedContacts. I'd be very grateful if you could tell me how to fix the problem.
I am quite sure it has to do with something around this line:
//get the other data related to the selected contact - name and number
SelectPhoneContact contact = (SelectPhoneContact) checkbox.getTag();
I am not getting any errors but when I run in debug mode it gets to here and then jumps to:
} catch (Exception e) {
System.out.println("there's a problem here unfortunately");
e.printStackTrace();
}
I think it has something to do with setTag but I find it confusing and I'm not sure where it should be set (if, even, that is the problem).
I'm posting the relevant code for my activity, NewContact and the RecyclerViewAdapter, PopulistoCOntactsAdapter. Thanks for any help.
NewContact.java
//for the SAVE button
private void saveContactButton() {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("you clicked it, save");
try {
System.out.println("we're in the try part");
int count = MatchingContactsAsArrayList.size();
for (int i = 0; i < count; i++) {
//for each Matching Contacts row in the listview
LinearLayout itemLayout = (LinearLayout)recyclerView.getChildAt(i); // Find by under LinearLayout
//for each Matching Contacts checkbox in the listview
CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.checkBoxContact);
//get the other data related to the selected contact - name and number
SelectPhoneContact contact = (SelectPhoneContact) checkbox.getTag();
//if that checkbox is checked, then get the phone number
if(checkbox.isChecked()) {
Log.d("Item " + String.valueOf(i), checkbox.getTag().toString());
Toast.makeText(NewContact.this, contact.getPhone(), Toast.LENGTH_LONG).show();
// make each checked contact in selectPhoneContacts
// into an individual
// JSON object called checkedContact
JSONObject checkedContact = new JSONObject();
// checkedContact will be of the form {"checkedContact":"+353123456"}
checkedContact.put("checkedContact", contact.getPhone());
// Add checkedContact JSON Object to checkedContacts jsonArray
//The JSON Array will be of the form
// [{"checkedContact":"+3531234567"},{"checkedContact":"+353868132813"}]
//we will be posting this JSON Array to Php, further down below
checkedContacts.put(checkedContact);
System.out.println("NewContact: checkedcontact JSONObject :" + checkedContact);
}
}
} catch (Exception e) {
System.out.println("there's a problem here unfortunately");
e.printStackTrace();
}
//When the user clicks save
//post phoneNoofUserCheck to NewContact.php and from that
//get the user_id in the user table, then post category, name, phone etc...
//to the review table
StringRequest stringRequest = new StringRequest(Request.Method.POST, NewContact_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response, this will show the checked numbers being posted
Toast.makeText(NewContact.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
//post these details to the NewContact.php file and do
//stuff with it
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//post the phone number to php to get the user_id in the user table
params.put("phonenumberofuser", phoneNoofUserCheck);
//the second value, categoryname.getText().toString() etc...
// is the value we get from Android.
//the key is "category", "name" etc.
// When we see these in our php, $_POST["category"],
//put in the value from Android
params.put("category", categoryname.getText().toString());
params.put("name", namename.getText().toString());
params.put("phone", phonename.getText().toString());
params.put("address", addressname.getText().toString());
params.put("comment", commentname.getText().toString());
params.put("public_or_private", String.valueOf(public_or_private));
System.out.println("public_or_private is " + String.valueOf(public_or_private));
//this is the JSON Array of checked contacts
//it will be of the form
//[{"checkedContact":"+3531234567"},{"checkedContact":"+353868132813"}]
params.put("checkedContacts", checkedContacts.toString());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
//when saved, go back to the PopulistoListView class and update with
//the new entry
Intent j = new Intent(NewContact.this, PopulistoListView.class);
j.putExtra("phonenumberofuser", phoneNoofUserCheck);
NewContact.this.startActivity(j);
finish();
}
});
}
}
PopulistoContactsAdapter.java
public class PopulistoContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//make a List containing info about SelectPhoneContact objects
public List<SelectPhoneContact> theContactsList;
Context context_type;
public class MatchingContact extends RecyclerView.ViewHolder {
//In each recycler_blueprint show the items you want to have appearing
public TextView title, phone;
public CheckBox check;
public Button invite;
public MatchingContact(final View itemView) {
super(itemView);
//title is cast to the name id, in recycler_blueprint,
//phone is cast to the id called no etc
title = (TextView) itemView.findViewById(R.id.name);
phone = (TextView) itemView.findViewById(R.id.no);
invite = (Button) itemView.findViewById(R.id.btnInvite);
check = (CheckBox) itemView.findViewById(R.id.checkBoxContact);
}
}
public class nonMatchingContact extends RecyclerView.ViewHolder {
//In each recycler_blueprint show the items you want to have appearing
public TextView title, phone;
public CheckBox check;
public Button invite;
public nonMatchingContact(final View itemView) {
super(itemView);
//title is cast to the name id, in recycler_blueprint,
//phone is cast to the id called no etc
title = (TextView) itemView.findViewById(R.id.name);
phone = (TextView) itemView.findViewById(R.id.no);
invite = (Button) itemView.findViewById(R.id.btnInvite);
check = (CheckBox) itemView.findViewById(R.id.checkBoxContact);
}
}
#Override
public int getItemViewType(int position) {
//for each row in recyclerview, get the getType_row, set in NewContact.java
return Integer.parseInt(theContactsList.get(position).getType_row());
}
public PopulistoContactsAdapter(List<SelectPhoneContact> selectPhoneContacts, Context context) {
//selectPhoneContacts = new ArrayList<SelectPhoneContact>();
theContactsList = selectPhoneContacts;
// whichactivity = activity;
context_type = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
//if getType_row is 1...
if (viewType == 1)
{
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.recycler_blueprint, parent, false);
//itemView.setTag();
return new MatchingContact(itemView);
} else {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.recycler_blueprint_non_matching, parent, false);
return new nonMatchingContact(itemView);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
//bind the views into the ViewHolder
//selectPhoneContact is an instance of the SelectPhoneContact class.
//We will assign each row of the recyclerview to contain details of selectPhoneContact:
//The number of rows will match the number of phone contacts
final SelectPhoneContact selectPhoneContact = theContactsList.get(position);
if (viewHolder.getItemViewType() == 1)
{
((MatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((MatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
CheckBox check = ((MatchingContact) viewHolder).check;
//get the number position of the checkbox in the recyclerview
//check.setTag(position);
}
else {
((nonMatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((nonMatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
}
}
#Override
public int getItemCount() {
return theContactsList.size();
}
}
And here is my SelectPhoneContact class:
public class SelectPhoneContact {
String phone;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
boolean isMatching;
public boolean isMatching(){return isMatching;}
public void setIsMatchingContact(boolean isMatching){
this.isMatching = isMatching;
}
//*****************************************
//this is for the checkbox
boolean selected = false;
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
String type_row;
public String getType_row() {
return type_row;
}
public void setType_row(String type_row) {
this.type_row = type_row;
}
}
I figured it out. This tutorial was very helpful: https://demonuts.com/2017/07/03/recyclerview-checkbox-android/
Here is the code I used for NewContact.java:
//for the SAVE button
private void saveContactButton() {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("you clicked it, save");
try {
System.out.println("we're in the try part");
//loop through the matching contacts
int count = MatchingContactsAsArrayList.size();
for (int i = 0; i < count; i++) {
//for matching contacts that are checked...
if (PopulistoContactsAdapter.theContactsList.get(i).getSelected()) {
Toast.makeText(NewContact.this, PopulistoContactsAdapter.theContactsList.get(i).getPhone() + " clicked!", Toast.LENGTH_SHORT).show();
// make each checked contact in selectPhoneContacts
// into an individual
// JSON object called checkedContact
JSONObject checkedContact = new JSONObject();
// checkedContact will be of the form {"checkedContact":"+353123456"}
checkedContact.put("checkedContact", PopulistoContactsAdapter.theContactsList.get(i).getPhone());
// Add checkedContact JSON Object to checkedContacts jsonArray
//The JSON Array will be of the form
// [{"checkedContact":"+3531234567"},{"checkedContact":"+353868132813"}]
//we will be posting this JSON Array to Php, further down below
checkedContacts.put(checkedContact);
System.out.println("NewContact: checkedcontact JSONObject :" + checkedContact);
}
}
} catch (Exception e) {
System.out.println("there's a problem here unfortunately");
e.printStackTrace();
}
//When the user clicks save
//post phoneNoofUserCheck to NewContact.php and from that
//get the user_id in the user table, then post category, name, phone etc...
//to the review table
StringRequest stringRequest = new StringRequest(Request.Method.POST, NewContact_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response, this will show the checked numbers being posted
Toast.makeText(NewContact.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
//post these details to the NewContact.php file and do
//stuff with it
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//post the phone number to php to get the user_id in the user table
params.put("phonenumberofuser", phoneNoofUserCheck);
//the second value, categoryname.getText().toString() etc...
// is the value we get from Android.
//the key is "category", "name" etc.
// When we see these in our php, $_POST["category"],
//put in the value from Android
params.put("category", categoryname.getText().toString());
params.put("name", namename.getText().toString());
params.put("phone", phonename.getText().toString());
params.put("address", addressname.getText().toString());
params.put("comment", commentname.getText().toString());
params.put("public_or_private", String.valueOf(public_or_private));
System.out.println("public_or_private is " + String.valueOf(public_or_private));
//this is the JSON Array of checked contacts
//it will be of the form
//[{"checkedContact":"+3531234567"},{"checkedContact":"+353868132813"}]
params.put("checkedContacts", checkedContacts.toString());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
//when saved, go back to the PopulistoListView class and update with
//the new entry
Intent j = new Intent(NewContact.this, PopulistoListView.class);
j.putExtra("phonenumberofuser", phoneNoofUserCheck);
NewContact.this.startActivity(j);
finish();
}
});
}
}
And my PopulistoContactsAdapter.java:
public class PopulistoContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//make a List containing info about SelectPhoneContact objects
public static List<SelectPhoneContact> theContactsList;
Context context_type;
public class MatchingContact extends RecyclerView.ViewHolder {
//In each recycler_blueprint show the items you want to have appearing
public TextView title, phone;
public CheckBox check;
public Button invite;
public MatchingContact(final View itemView) {
super(itemView);
//title is cast to the name id, in recycler_blueprint,
//phone is cast to the id called no etc
title = (TextView) itemView.findViewById(R.id.name);
phone = (TextView) itemView.findViewById(R.id.no);
invite = (Button) itemView.findViewById(R.id.btnInvite);
check = (CheckBox) itemView.findViewById(R.id.checkBoxContact);
}
}
public class nonMatchingContact extends RecyclerView.ViewHolder {
//In each recycler_blueprint show the items you want to have appearing
public TextView title, phone;
public CheckBox check;
public Button invite;
public nonMatchingContact(final View itemView) {
super(itemView);
//title is cast to the name id, in recycler_blueprint,
//phone is cast to the id called no etc
title = (TextView) itemView.findViewById(R.id.name);
phone = (TextView) itemView.findViewById(R.id.no);
invite = (Button) itemView.findViewById(R.id.btnInvite);
check = (CheckBox) itemView.findViewById(R.id.checkBoxContact);
}
}
#Override
public int getItemViewType(int position) {
//for each row in recyclerview, get the getType_row, set in NewContact.java
return Integer.parseInt(theContactsList.get(position).getType_row());
}
public PopulistoContactsAdapter(List<SelectPhoneContact> selectPhoneContacts, Context context) {
//selectPhoneContacts = new ArrayList<SelectPhoneContact>();
theContactsList = selectPhoneContacts;
// whichactivity = activity;
context_type = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
//if getType_row is 1...
if (viewType == 1)
{
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.recycler_blueprint, parent, false);
//itemView.setTag();
return new MatchingContact(itemView);
} else {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.recycler_blueprint_non_matching, parent, false);
return new nonMatchingContact(itemView);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
//bind the views into the ViewHolder
//selectPhoneContact is an instance of the SelectPhoneContact class.
//We will assign each row of the recyclerview to contain details of selectPhoneContact:
//The number of rows will match the number of phone contacts
final SelectPhoneContact selectPhoneContact = theContactsList.get(position);
if (viewHolder.getItemViewType() == 1)
{
((MatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((MatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
((MatchingContact) viewHolder).check.setText("Cheeckbox" + position);
((MatchingContact) viewHolder).check.setChecked(theContactsList.get(position).getSelected());
((MatchingContact) viewHolder).check.setTag(position);
((MatchingContact) viewHolder).check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer pos = (Integer) ((MatchingContact) viewHolder).check.getTag();
Toast.makeText(context_type, theContactsList.get(pos).getPhone() + " clicked!", Toast.LENGTH_SHORT).show();
if (theContactsList.get(pos).getSelected()) {
theContactsList.get(pos).setSelected(false);
} else {
theContactsList.get(pos).setSelected(true);
}
}
});
// CheckBox check = ((MatchingContact) viewHolder).check;
//get the number position of the checkbox in the recyclerview
//check.setTag(position);
}
else {
((nonMatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((nonMatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
}
}
#Override
public int getItemCount() {
return theContactsList.size();
}
}
I made a custom adapter that displays objects in Listview and an icon for each item in list. There are 3 icons that show next to an item in the list view. User can select option "Kupljeno" which changes Status of object to 1, option "Nije kupljeno" to 0 and "Nije dostupno" to 2. Each number represents a different icon, you can that in getView() function of Adapter class. The adapter class looks like this:
public class ListaAdapter extends ArrayAdapter<Proizvod> {
public ListaAdapter(Context context, ArrayList<Proizvod> proizvodi) {
super(context, 0, proizvodi);
}
public void remove(int position) {
this.remove(getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
Proizvod proizvod = getItem(position);
if(convertView==null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.shoppinglista_prikazproizvoda,parent,false);
TextView t = (TextView)convertView.findViewById(R.id.text1);
t.setText(proizvod.toString());
switch(proizvod.getStatus())
{
case 0:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_nijekupljeno, 0);
break;
case 1:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_kupljeno, 0);
break;
case 2:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_nedostupno, 0);
break;
}
}
return convertView;
}
}
You can see that I set icon of each item in getView().
The user should be able to change Status of each Proizvod object with a context menu and when the user chooses object Status, the list should update and show the appropriate icon.
My Proizvod class is this:
public class Proizvod {
private int id;
private String naziv;
private int kolicina=1;
private double cijena;
private String lista;
public int status=0; //0 - nije kupljeno, 1 - kupljeno, 2 - nedostupno
public Proizvod() {
}
public Proizvod(int id, String naziv, int kolicina, double cijena, String lista, int status) {
this.id = id;
this.naziv = naziv;
this.kolicina = kolicina;
this.cijena = cijena;
this.status = status;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public int getKolicina() {
return kolicina;
}
public void setKolicina(int kolicina) {
this.kolicina = kolicina;
}
public double getCijena() { return cijena; }
public void setCijena(double cijena) {
this.cijena = cijena;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLista() { return lista; }
public void setLista(String lista) { this.lista = lista; }
public int getStatus() { return status; }
public void setStatus(int status) { this.status = status; }
#Override
public String toString() {
if(this.kolicina==1) {
return this.naziv + " ["+ this.kolicina +" komad, ukupno " + this.cijena + " kn ]";
}
else {
return this.naziv + " ["+ this.kolicina +" komada, ukupno " + this.cijena + " kn ]";
}
}
}
The code for context menu and changing icon (activity):
public class KreiranjeListeActivity extends AppCompatActivity {
ArrayList<Proizvod> ShoppingLista = new ArrayList<Proizvod>();
EditText nazivProizvoda;
EditText kolicina;
EditText cijena;
Button dodaj;
Button ocisti;
Button spremi;
ListView lista;
ListaAdapter adapter;
//Funkcija vraća ukupan iznos svih stavki u listi
public void AzurirajUkupniTrosak() {
DecimalFormat zaokruzi=new DecimalFormat("0.00");
double ukupniIznos=0;
for(Proizvod p : ShoppingLista)
{
ukupniIznos+=p.getCijena();
}
String ukupniIznosString=zaokruzi.format(ukupniIznos);
TextView prikazUkupnogIznosa=(TextView)findViewById(R.id.textView_ukupaniznos);
prikazUkupnogIznosa.setText("Ukupno: " + ukupniIznosString + " kn");
}
//Funkcija otvara meni dužim pritiskom na stavku u listi i nudi opciju brisanja stavke
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if (v.getId() == R.id.shoppinglista2_list) {
ListView lv = (ListView) v;
AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
Proizvod proizvod = (Proizvod) lv.getItemAtPosition(acmi.position);
menu.add(200,201,1,"Obriši");
menu.add(200,202,2,"Kupljeno");
menu.add(200,203,3,"Nije kupljeno");
menu.add(200,204,4,"Proizvod je nedostupan");
menu.add(200,205,5,"Zatvori prozor");
}
}
//funkcija u kojoj se sa adaptera briše odabrana stavka, iste promjene se automatski primijene i na listu
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case 201:
adapter.remove(info.position);
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
return true;
case 202:
ShoppingLista.get(info.position).setStatus(1);
adapter.notifyDataSetChanged();
return true;
case 203:
ShoppingLista.get(info.position).setStatus(0);
adapter.notifyDataSetChanged();
return true;
case 204:
ShoppingLista.get(info.position).setStatus(2);
adapter.notifyDataSetChanged();
return true;
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kreiranje_liste);
final DBHandler db = new DBHandler(this);
nazivProizvoda=(EditText)findViewById(R.id.nazivproizvoda_text);
kolicina=(EditText)findViewById(R.id.kolicinaproizvoda_text);
cijena=(EditText)findViewById(R.id.cijenaproizvoda_text);
dodaj=(Button)findViewById(R.id.dodaj_gumb);
ocisti=(Button)findViewById(R.id.ocisti_gumb);
spremi=(Button)findViewById(R.id.spremi_gumb);
lista=(ListView)findViewById(R.id.shoppinglista2_list);
registerForContextMenu(lista);
adapter = new ListaAdapter(this,ShoppingLista);
lista.setAdapter(adapter);
dodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////////////PROVJERE KOD UPISA ///////////////////////
if(TextUtils.isEmpty(nazivProizvoda.getText())) {
nazivProizvoda.setError("Unesite naziv proizvoda!");
return;
}
if(TextUtils.isEmpty(cijena.getText())) {
cijena.setError("Unesite cijenu!");
return;
}
if(TextUtils.isEmpty(kolicina.getText())) {
kolicina.setError("Unesite količinu!");
return;
}
if((kolicina.getText().toString()).contains(".")) {
kolicina.setError("Unesite ispravan broj!");
return;
}
/////////////PROVJERE KOD UPISA -KRAJ ////////////////////////
DecimalFormat zaokruzi=new DecimalFormat("0.00");
Proizvod p = new Proizvod();
p.setNaziv(nazivProizvoda.getText().toString());
p.setKolicina(Integer.parseInt(kolicina.getText().toString()));
String ukupnaCijena=zaokruzi.format(Float.parseFloat(cijena.getText().toString())*Integer.parseInt(kolicina.getText().toString())).toString();
p.setCijena(Double.parseDouble(ukupnaCijena)); //množi se količina sa cijenom jednog komada proizvoda
ShoppingLista.add(p);
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
Toast.makeText(getApplicationContext(), "Proizvod dodan u listu!",
Toast.LENGTH_SHORT).show();
nazivProizvoda.setText("");
kolicina.setText("");
cijena.setText("");
}
});
ocisti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShoppingLista.clear();
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
Toast.makeText(getApplicationContext(), "Proizvodi su obrisani!",
Toast.LENGTH_SHORT).show();
}
});
spremi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(KreiranjeListeActivity.this);
View promptsView = li.inflate(R.layout.spremanje_liste, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
KreiranjeListeActivity.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText nazivListe = (EditText) promptsView
.findViewById(R.id.nazivListe);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Spremi",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
ShoppingLista shoppinglista = new ShoppingLista(nazivListe.getText().toString(),"TEST DATUMA");
/////POSTAVLJANJE UKUPNOG IZNOSA U NOVOSTVORENU LISTU
DecimalFormat zaokruzi=new DecimalFormat("0.00");
double ukupniIznos=0;
for(Proizvod p : ShoppingLista)
{
ukupniIznos+=p.getCijena();
}
//////////////////////////////////////////////////////
db.dodajListu(shoppinglista);
for(Proizvod p : ShoppingLista)
{
db.dodajProizvod(p,nazivListe.getText().toString());
}
Intent i = new Intent(KreiranjeListeActivity.this, PopisListaActivity.class);
startActivity(i);
}
})
.setNegativeButton("Otkaži",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
}
The problem is that the icons don't change at all. The value of Status of a selected object changes but the icon doesn't, even though I use adapter.notifyDataSetChanged(); What's wrong?
Here change this in your code in your List adapter class:
First create a list of type Proizvod
List<Proizvod> dataList = new ArrayList<>();
then
public ListaAdapter(Context context, ArrayList<Proizvod> proizvodi) {
super(context, 0, proizvodi);
this.dataList = proizvodi;
}
In place of Proizvod proizvod = getItem(position);
use
Proizvod proizvod = dataList.getItem(position);
Hope it helps!!!
I have alertdialog with custom checkboxes, i need to pass the selected choices to the host activity, and persist the selected choices. here is my code :
public class TimelineSettings extends DialogFragment {
ArrayList<Integer> selected_categories = new ArrayList<Integer>();
boolean[] itemsChecked = {false, false, false, false, false, false};
private FlatCheckBox fourniture,nourriture,voyages,habillement,medias,autres;
public interface dialoglistener {
public void onOkay(ArrayList<Integer> selected);
public void onCancel();
}
dialoglistener mlistener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// ensure that the host activity implements the callback interface
try {
// Instantiate the dialogListener so we can send events to the host
mlistener = (dialoglistener) activity;
} catch (ClassCastException e) {
// if activity doesn't implement the interface, throw an exception
throw new ClassCastException(activity.toString()
+ " must implement dialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = LayoutInflater.from(getActivity());
View custom = inflater.inflate(R.layout.custom_settings,null);
fourniture = (FlatCheckBox)custom.findViewById(R.id.fourniture);
nourriture = (FlatCheckBox)custom.findViewById(R.id.nourriture);
voyages = (FlatCheckBox)custom.findViewById(R.id.voyages);
habillement = (FlatCheckBox)custom.findViewById(R.id.habillement);
medias = (FlatCheckBox)custom.findViewById(R.id.medias);
autres = (FlatCheckBox)custom.findViewById(R.id.autres);
if (selected_categories.contains(0)){
fourniture.setChecked(true);
}
if (selected_categories.contains(1)){
nourriture.setChecked(true);
}
if (selected_categories.contains(2)){
voyages.setChecked(true);
}
if (selected_categories.contains(3)){
habillement.setChecked(true);
}
if (selected_categories.contains(4)){
medias.setChecked(true);
}
if (selected_categories.contains(5)){
autres.setChecked(true);
}
builder.setView(custom)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
checkboxState();
mlistener.onOkay(selected_categories);
}
})
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mlistener.onCancel();
}
});
return builder.create();
}
public void checkboxState(){
if (fourniture.isChecked()){
if(!selected_categories.contains(0)){
selected_categories.add(0);
itemsChecked[0]=true;
}
else if (selected_categories.contains(0)) {
// Else, if the item is already in the array, remove it
selected_categories.remove(0);
itemsChecked[0]=false;
}
}
if (nourriture.isChecked()){
if(!selected_categories.contains(1)){
selected_categories.add(1);
itemsChecked[1]=true;
}
else if (selected_categories.contains(1)) {
selected_categories.remove(1);
itemsChecked[1]=false;
}
}
if (voyages.isChecked()){
if(!selected_categories.contains(2)){
selected_categories.add(2);
itemsChecked[2]=true;
}
else if (selected_categories.contains(2)) {
selected_categories.remove(2);
itemsChecked[2]=false;
}
}
if (habillement.isChecked()){
if(!selected_categories.contains(3)){
selected_categories.add(3);
itemsChecked[3]=true;
}
else if (selected_categories.contains(3)) {
selected_categories.remove(3);
itemsChecked[3]=false;
}
}
if (medias.isChecked()){
if(!selected_categories.contains(4)){
selected_categories.add(4);
itemsChecked[4]=true;
}
else if (selected_categories.contains(4)) {
selected_categories.remove(4);
itemsChecked[4]=false;
}
}
if (autres.isChecked()){
if(!selected_categories.contains(5)){
selected_categories.add(5);
itemsChecked[5]=true;
}
else if (selected_categories.contains(5)) {
selected_categories.remove(5);
itemsChecked[5]=false;
}
}
}
}
this code works fine, but it does not look so! too much if elses...
my question is if there is a way to use a loop on my checkboxes to get their state, and then to set the elements of the array itemschecked to true/false for the persistency.
thanks !
Keep an array of FlatCheckBoxs:
private FlatCheckBox [] check = new FlatCheckBox[6];
and use an enum to retrive what checkbox you need:
private enum Names
{
fourniture(0),
nourriture(1),
voyages(2),
habillement(3),
medias(4),
autres(5);
private int val;
Names(int a)
{
val = a;
}
public int get()
{
return val;
}
};
Now use:
public void checkboxState()
{
for(FlatCheckBox fb : check)
{
if (fb.isChecked())
{
}
}
}
And you can access individual elements of the array like this:
FlatCheckBox fourniture = check[Names.fourniture.get()];
I would use the enum for a better readability, using [0], [1] ... can be confusing and lead to programming errors.