dynamic way to work with checkboxes - java

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.

Related

Call non-static method in Static method JAVA

EDITED:
The real purpose of that is to have one activity and on class who fetch data and render it to the activity.
The problem is I have dropdown menu. When I clicked on an item of the menu it change my url but it does not load or fetch my data to the activity but when i clicked again it works but with the paramaters selected just before and if I clicked again it still works but still with the previous elements selected.
My "teacher" said I have to call build into my callback method.
But it doesen't work at all. And I still didn't find any solution :/.
As you recommended I changed everything for non-static method
I thought why not saving an history of the dropdown, compare the current value with the saved value and if it's diffrent it means it was changed so reload the app to make new fetch and displyed new data.
But I got :
Here my all code
PhotosActivity
public class PhotosActivity extends AppCompatActivity {
// Local variable
private OkHttpClient httpClient;
private ImageButton home_btn;
private ImageButton favorites_btn;
private ImageButton search_btn;
private ImageButton profil_btn;
// Constante variable
private static final String TAG = "PhotoActivity";
private static final String clientId = "bb0c749c6403fd2";
// Private shared variable
private static List<Photo> mPhotos;
private static JSONArray mItems;
private static String mAccessToken;
private static String userID;
static Activity activity;
// Shared variable
private static String selectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
this.home_btn = findViewById(R.id.home_button);
this.favorites_btn = findViewById(R.id.favorites_button);
this.search_btn = findViewById(R.id.search_button);
this.profil_btn = findViewById(R.id.profil_button);
final HttpHandler httpHandler = new HttpHandler();
httpHandler.fetchData();
build();
activity = this;
Spinner spinner=(Spinner)findViewById(R.id.spinner);
String[] filters=getResources().getStringArray(R.array.filters);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinner,R.id.text, filters);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
selectedItem = parent.getItemAtPosition(position).toString();
// httpHandler.fetchData();
// build();
}
public void onNothingSelected(AdapterView<?> parent)
{
Log.d("TAG", "Error");
}
});
home_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), PhotosActivity.class);
finish();
startActivity(next_activity);
}
});
favorites_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
finish();
startActivity(next_activity);
}
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), SearchActivity.class);
finish();
startActivity(next_activity);
}
});
profil_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), ProfileActivity.class);
finish();
startActivity(next_activity);
}
});
}
public void Filters() {
String hSection;
String hSort;
String hShowV;
hSection = HttpHandler.section ;
hSort = HttpHandler.sort;
hShowV = HttpHandler.showV;
Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
if(selectedItem != null) {
if (selectedItem.equals("Most Viral")) {
HttpHandler.sort = "viral/";
HttpHandler.section = "hot/";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "most: "+HttpHandler.section);
Log.d("TAG", "H most: "+hSection);
// activity.recreate();
// onRestart();
finish();
startActivity(next_activity);
}
} else if (selectedItem.equals("Newest")) {
HttpHandler.section = "top/";
HttpHandler.sort = "time/";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "new: "+HttpHandler.section);
Log.d("TAG", "H new: "+hSection);
finish();
startActivity(next_activity);
// activity.recreate();
// onRestart();
}
} else if (selectedItem.equals("Rising")) {
HttpHandler.section = "user/";
HttpHandler.sort = "rising/";
HttpHandler.showV = "?showViral=false";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "rising: "+HttpHandler.section);
Log.d("TAG", "H rising: "+hSection);
// onRestart();
// activity.recreate();
finish();
startActivity(next_activity);
}
} else {
Log.d(TAG, "Might be a problem");
}
} else {
activity.recreate();
}
}
public void build () {
try {
for(int i = 0; i < mItems.length(); i++) {
JSONObject item = mItems.getJSONObject(i);
Photo photo = new Photo();
if(item.getBoolean("is_album")) {
photo.id = item.getString("cover");
} else {
photo.id = item.getString("id");
}
photo.title = item.getString("title");
mPhotos.add(photo);
runOnUiThread(new Runnable() {
#Override
public void run() {
render(mPhotos);
}
});
}
} catch (Exception e) {
Log.e("JSONerr" , "Something went wrong.");
}
}
private static class PhotoVH extends RecyclerView.ViewHolder {
ImageView photo;
TextView title;
public PhotoVH(View itemView) {
super(itemView);
}
}
private void render(final List<Photo> photos) {
RecyclerView rv = (RecyclerView)findViewById(R.id.rv_of_photos);
rv.setLayoutManager(new LinearLayoutManager(this));
RecyclerView.Adapter<PhotoVH> adapter = new RecyclerView.Adapter<PhotoVH>() {
#NonNull
#Override
public PhotoVH onCreateViewHolder(ViewGroup parent, int viewType) {
PhotoVH vh = new PhotoVH(getLayoutInflater().inflate(R.layout.item, null));
vh.photo = (ImageView) vh.itemView.findViewById(R.id.photo);
vh.title = (TextView) vh.itemView.findViewById(R.id.title);
return vh;
}
#Override
public void onBindViewHolder(PhotoVH holder, int position) {
Picasso.with(PhotosActivity.this).load("https://i.imgur.com/" +
photos.get(position).id + ".jpg").into(holder.photo);
holder.title.setText(photos.get(position).title);
}
#Override
public int getItemCount() {
return photos.size();
}
};
rv.setAdapter(adapter);
}
public static void getUserID(String UserID) {
Log.d("TAG", UserID);
userID = UserID;
}
public void callBackPhoto( List<Photo> photos, JSONArray items)
{
mPhotos = photos;
mItems = items;
// build();
}
}
HttpHandler
public class HttpHandler {
private static final String TAG = "HttpHandler";
private static String clientId = "bb0c749c6403fd2";
private static OkHttpClient httpClient;
private static String mAccessToken;
// URL BUILDER VARIABLES
public static String section = "hot/";
public static String sort = "viral/";
public static String page;
public static String showV;
public static String mUrl;
public void fetchData() {
httpClient = new OkHttpClient.Builder().build();
photosActivity.Filters();
mUrl = "https://api.imgur.com/3/gallery/" + section + sort;
// Log.d("TAG", "Sort: " + sort + ": URl is" + mUrl);
Request request = new Request.Builder()
.url(mUrl + "0.json" + showV)
.addHeader("Authorization", "Client-ID " + clientId)
.header("User-Agent", "epicture")
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "An error has occurred " + e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject data = new JSONObject(response.body().string());
JSONArray items = data.getJSONArray("data");
final List<Photo> photos = new ArrayList<Photo>();
photosActivity.callBackPhoto(photos, items);
} catch (Exception e) {
Log.e("JSONerr", "Something went wrong.");
}
}
});
}
public static void getLoginData(String accessToken) {
mAccessToken = accessToken;
}
}
It doesn't look like making sense to declare callBackPhoto as a static method. If you have put static keyword accidentally in its declaration, simply remove it to solve your problem i.e. replace
public static void callBackPhoto( List<Photo> photos, JSONArray items)
with
public void callBackPhoto( List<Photo> photos, JSONArray items)
Note that there is no way to call a non-static method from a static one directly (i.e. without calling it on an object/instance). Thus, if for any reason, you can't remove static keyword from the declaration of callBackPhoto, you are left with only two options:
Declare build too as static
Call build on an object/instance e.g. new PhotosActivity().build()
Though any of these two options will solve your problem, I don't think this is how you intend to design your class.
In java, a static method belongs to EVERY object of the class that defines it. Therefore, you can call it from the parent class without creating an object like so:
ParentClass.myMethod;
However, this is not the case the case with instance (non-static) methods. To call this type of method, you need to define it in a class, create an object from that class, and then call it from that object, like this:
//inside ParentClass definition
public void myMethod(){bla bla;}
//In some other class
ParentClass obj = new ParentClass;
obj.myMethod;
Suppose you have code calling a static member of a class without creating an instance of that class. If that method contained a non-static method, there would be no object in memory to call it on. This is why it isn't possible.
Static
The static methods are alive all the time. They live from the class is loaded. They don't need objects to live. I think of them as not really belonging to the class, but the class is just a nice way to organize those methods (the same for variables). The methods could be put in any other class definition and it would still work. But organizing them in classes where they will be used make it easy to prevent access from other parts of the program, like other objects or other static methods. They are called class methods or class variables.
Instance
The non-static "stuff" does not live unless there is an object. That's why you cannot call below methodOne or methodTwo from the static methods. You have to create an object first. They are called instance methods or instance variables, because you need an instance of an object to call them.
Error
error: non-static method <methodname> cannot be referenced from a static context basically means "There's no object"
Example
public class StackOverflowTest {
public static void main(String[] args) { // this is just another static method
// methodOne(); // error. There's no object
StackOverflowTest test = new StackOverflowTest();
test.methodOne(); // method called on object.
}
// methods live outside objects
static void staticMethodOne() {
System.out.println("staticMethodOne");
staticMethodTwo(); // no object required.
}
static void staticMethodTwo() {
System.out.println("staticMethodTwo");
// methodTwo(); // error. There's no object
}
// methods that only live inside objects
void methodOne() { // method can only be invoked if there's an object.
System.out.println("methodOne");
methodTwo(); // no problem. Already inside the object.
}
void methodTwo() {
System.out.println("methodTwo");
staticMethodTwo(); // no problem. Objects can access static methods.
}
}
Your case
So you either have to create a PhotosActivity object inside your build(), or you have to make callBackPhoto a static method. I can't see what your render does, but it's the same principle.

Issue with RecyclerView data interchanges while scrolling

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();
}
}
});
}

ArrayIndexOutOfBoundsException / passing arraylist from alertdialog to activity

I have an alertdialog with multiple choices, I store the user's choices on an ArrayList of strings, and I want to pass the stored arraylist to the host activity (I will use the array's elements to query my database)..
When i run my app, i get an ArrayIndexOutOfBoundsException (may be the index is -1..), I'm not sure if it's the loop, or if i did not pass the arraylist correctly from the alertdialog...
can you guys take a look ? here is my function :
public void onOkay(ArrayList<String> selected) {
StringBuilder stringBuilder = new StringBuilder();
if (selected.size() != 0) {
for (int i = 0; i < selected.size(); i++) {
String categories = selected_items_array[selected.indexOf(i)];
stringBuilder = stringBuilder.append(" " + categories);
}
Toast.makeText(this, "You have selected: "
+ stringBuilder.toString(), Toast.LENGTH_SHORT).show();
}
}
logcat :
java.lang.ArrayIndexOutOfBoundsException: length=6; index=-1
at com.hichamridouane.smartshop.MainActivity.onOkay(MainActivity.java:164)
at com.hichamridouane.smartshop.TimelineSettings$2.onClick(TimelineSettings.java:71)
here is my dialogfragment class.
and here is my host activity.(as I said, i'm not sure if i'm passing correctly the arraylist to the host activity)
thanks !
It looks really strange to me, especially in
String categories = selected_items_array[selected.indexOf(i)];
From JavaDocs about indexOf
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
More formally, returns the lowest index <tt>i</tt> such that
<tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
or -1 if there is no such index.
So, you try to find element in your selected_items_array (not correct name in Java)
in first iteration i == 0, selected_items_array have no such element => indexOf return -1. Array can't have element with index = -1, it starts from 0. So you have your ArrayIndexOutOfBoundsException
Problem solved. Had to use Arraylists of integers in my activity and my dialogfragment.
here is what i did in my DialogFragment class:
public class TimelineSettings extends DialogFragment {
ArrayList<Integer> selected_categories = new ArrayList<Integer>();
boolean[] itemsChecked = {false, false, false, false, false, false};
// this interface to communicate with the host activity.
public interface dialoglistener {
public void onOkay(ArrayList<Integer> selected);
public void onCancel();
}
dialoglistener mlistener;
//this function is to instantiate the dialoglistener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mlistener = (dialoglistener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement dialogListener");
}
}
My multichoice dialog :
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
for(int i=0;i<itemsChecked.length;i++){
if(selected_categories.contains((String)String.valueOf(i)))
itemsChecked[i]=true;
}
// Set the dialog title
builder.setTitle("Choisissez vos paramètres")
.setMultiChoiceItems(R.array.categories, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexselected,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
if(!selected_categories.contains(indexselected)){
selected_categories.add(indexselected);
itemsChecked[indexselected]=true;
}
} else if (selected_categories.contains(indexselected)) {
// Else, if the item is already in the array, remove it
selected_categories.remove(indexselected);
itemsChecked[indexselected]=false;
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mlistener.onOkay(selected_categories);
}
})
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mlistener.onCancel();
}
});
return builder.create();
}
On my host activity, I implemented the fragment's interface :
#Override
public void onCreate(Bundle savedInstanceState) {
/* some fancy stuff */
Resources res = getResources();
selectedArray = res.getStringArray(R.array.categories);
}
Getting the selected items (and show them on a toast, just for testing) :
#Override
public void onOkay(ArrayList<Integer> selected) {
StringBuilder stringBuilder = new StringBuilder();
if (selected.size() != 0) {
for (int i = 0; i < selected.size(); i++) {
String categories = selectedArray[selected.get(i)];
stringBuilder = stringBuilder.append(" " + categories);
}
Toast.makeText(this, "You have selected: "
+ stringBuilder.toString(), Toast.LENGTH_SHORT).show();
}
}

Setting one element in array changes others

I checked other similar tags with almost same title. Those answers were not relevant
When setting element at one position of array, both the elements have the same value.
public class LogActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
startStopButton = (Button) findViewById(R.id.btnStart);
loggingStatusText = (TextView) findViewById(R.id.logStatusText);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
sensorValues=new ArrayList<float[]>(sensorList.size());
sensorValsArray=new float[sensorList.size()][];
sensorNameList = new ArrayList<String>();
selectedSensorNames = new ArrayList<String>();
for (Sensor itemSensor : sensorList)
{
if (itemSensor != null)
{
sensorNameList.add(itemSensor.getName());
}
}
showSensorList();
}
private void showSensorList()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setMultiChoiceItems((CharSequence[]) sensorNameList
.toArray(new CharSequence[sensorNameList.size()]),
new boolean[sensorNameList.size()],
new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked)
{
if (isChecked)
{
if (!selectedSensorNames.contains(sensorNameList
.get(whichButton)))
selectedSensorNames.add(sensorNameList
.get(whichButton));
} else
{
if (selectedSensorNames.contains(sensorNameList
.get(whichButton)))
{
selectedSensorNames.remove(sensorNameList
.get(whichButton));
}
}
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
listeners=new SensorEventListener[selectedSensorNames.size()];
float[] tempVals = new float[] { 0, 0, 0 };
for (int i = 0; i < selectedSensorNames.size(); i++)
{
sensorValsArray[i]=tempVals;
}
showRateList();
}
});
builder.setCancelable(false);
builder.create().show();
}
void registerSensors()
{
for (Sensor sensor : sensorList)
{
if (selectedSensorNames.contains(sensor.getName()))
{
mSensorManager.registerListener(listeners[selectedSensorNames.indexOf(sensor.getName())], sensor, selectedDelay);
}
}
}
class SchedulerTask extends TimerTask
{
/*
* The task to run should be specified in the implementation of the
* run() method
*/
public void run()
{
logSensorData();
}
}
private void createLog(String fileName)
{
File root = getExternalFilesDir(null);// Get the Android external
// storage directory
Date cDate = new Date();
String bstLogFileName = fileName;
bstLogFile = new File(root, bstLogFileName);// Construct a new file for
// using the specified
// directory and name
FileWriter bstLogWriter;
logScheduler = new Timer();// Create a new timer for updating values
// from content provider
logScheduler.schedule(new SchedulerTask(),
LOG_TASK_DELAY_IN_MILLISECONDS,
getLogPeriodInMilliSeconds(selectedDelay));
}
public void logSensorData()
{
Date stampDate = new Date();
String LogPack ="\r\n";
for (int count=0;count<selectedSensorNames.size();count++)
{
LogPack += sensorValsArray[count][0] + "," + sensorValsArray[count][1] + "," + sensorValsArray[count][2] + ",";
}
LogPack += "\r\n";
try
{
F_StreamWriter.write(LogPack);
F_StreamWriter.flush();
}
catch (IOException e)
{
}
catch (NullPointerException e)
{
}
}
public void startStopLog(View v)
{
if (startStopButton.getText().equals("Start"))
{
createSensorListeners();
registerSensors();
showFilenameDialog();
} else if (startStopButton.getText().equals("Stop"))
{
stopLog();
}
}
public void startLog(String fileName)
{
createLog(fileName);
}
public void stopLog()
{
logScheduler.cancel();
logScheduler.purge();
for(int i=0;i<listeners.length;i++)
mSensorManager.unregisterListener(listeners[i]);
}
private void showFilenameDialog()
{
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_text_input_dialog);
dialog.setCancelable(true);
final EditText fileNameInput = (EditText) dialog
.findViewById(R.id.fileNameText);
Button button = (Button) dialog.findViewById(R.id.okButton);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startLog(nameInput);
dialog.dismiss();
}
});
dialog.show();
}
private void createSensorListeners()
{
listeners=new SensorEventListener[selectedSensorNames.size()];
for (int i = 0; i < selectedSensorNames.size(); i++)
{
listeners[i]=new SensorEventListener()
{
#Override
public void onSensorChanged(SensorEvent event)
{
sensorValsArray[selectedSensorNames.indexOf(event.sensor.getName())]=event.values;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
};
}
}
}
When index is 0, when set command is executed, it also changes the the value at index position '1'.
Can anyone help me with this?
Thanks in Advance,
Dheepak
When index is 0, when set command is executed, it also changes the the value at index position '1'. Can anyone help me with this?
You are definitely mistaken as to what it is causing this. Setting the value at one position of an ArrayList WILL NOT mysteriously cause the value at another position to change. It simply does not work like that.
The effect you are observing will be due to something else:
maybe the value of index is not what you expect
maybe the value of event.values is not what you expect. (Maybe you've made a mistake in the way that you create the Event objects, and they are all sharing one float[] object.)
maybe the value at position 1 was already that value
maybe you've got multiple threads updating the sensorValues list.

ArrayList adding and removing Objects

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();
}

Categories

Resources