Add and remove item of recyclerview depending on distance - java

I am developing an application where a list of message (MESSAGE_RECIEVED) should be visible only in a certain distance (50, 100, 200, 300 or 400 meters)
For that I have an ArrayList of messages (MESSAGE_RECIEVED), a RecyclerView with a custom adapter and a fragment containing the RecyclerView and give it my ArrayList.
The methods I have now are the following:
To remove an entry (in my adapter):
public void removeAt(int pos) {
mMessagesList.remove(pos);
notifyItemRemoved(pos);
notifyItemRangeChanged(pos, mMessagesList.size());
}
To add an entry (in my adapter):
public void addAt(int pos, Message m){
mMessagesList.add(pos, m);
notifyItemInserted(pos);
}
Finaly my code that determine if an item is too far away:
ArrayList<String[]> operation = new ArrayList<>();
for (int i = 0; i < MESSAGES_RECEIVED.size(); i++){
if(dist <= distMax){
if(!MESSAGES_RECEIVED.get(i).isDisplayed()){
operation.add(new String[]{"add", String.valueOf(i)});
MESSAGES_RECEIVED.get(i).setDisplayed(true);
}
} else {
operation.add(new String[]{"remove", String.valueOf(i)});
}
}
for (String[] values : operation){
Log.i(TAG, "recalculateDistance: " + values[0] + " " + values[1]);
if(values[0].equals("add")){
int pos = Integer.valueOf(values[1]);
mRecyclerViewAdapter.addAt(pos, MESSAGES_RECEIVED.get(pos));
} else if(values[0].equals("remove")){
int pos = Integer.valueOf(values[1]);
mRecyclerViewAdapter.removeAt(pos);
}
}
This code do not work as items are removed from my ArrayList of message. I cannot delete them as they are used elsewhere (and I have IndexOutOfBoundsException because the position is out of the scope of the ArrayList).
On top of that I cannot delete them because if they are in the defined range people will not be able to see them.
Is there a way to hide items without deleting them? I though of duplicating my list of messages, don't know if this might work.
Thanks in advance guys!

Ok, I finally found somthing to make it works. I created another ArrayList and placed it in a static class (so that I can update the display from multiple place in the app)
Here is the methos I created
public static void updateDisplayedMessages(){
MESSAGES_DISPLAYED.clear();
getDistance(MESSAGES_RECEIVED);
for(Message m : MESSAGES_RECEIVED){
float dist = m.getDistance();
int distMax = Integer.valueOf(VALUE_PREF_RADIUS_GEO_FENCING);
if(dist < distMax){
MESSAGES_DISPLAYED.add(m);
}
}
}
Once this is called I call notifyDataSetChanged from my fragment and that's it! Probably not the most efficient way of implementing it but it works

Related

Metadata Item bug

I'm creating a mod for minecraft and created a metadata item, it has three variants (default, 1 and 2).
when im trying to give it to my player with item:0 or nothing i get this item, and its id is just item without :number, but when i give item:1, the given item adds to stack to item:0. When i throw item:0 from inventory, item:1 successfully gives with it custom texture, but its id is item, not item:1
Here's my item with variants code:
public Trowel(String name, CreativeTabs tab) {
super(name, tab);
this.tab = tab;
}
public void getSubItems(Item item, CreativeTabs tabs, List<ItemStack> list) {
for(int i = 0; i < EnumTrowel.count(); i++) {
list.add(new ItemStack(item, 1, i));
}
}
#Override
public String getUnlocalizedName(ItemStack stack) {
for(int i = 0; i < EnumTrowel.count(); i++) {
if(stack.getItemDamage() == i) {
return this.getUnlocalizedName() + "_" + EnumTrowel.values()[i].getName();
} else {
continue;
}
}
return this.getUnlocalizedName() + "_" + EnumTrowel.CLEAR.getName();
}
This is my Main class preInit()
public static void preInit(FMLPreInitializationEvent event) {
proxy.registerModelBakeryStuff();
RegistryHandler.registerCustomMeshesAndStates();
RegistryHandler.registerFluid(concrete);
for(int i = 0; i < EnumTrowel.count(); i++) {
ModItems.registerRender(ModItems.TROWEL, i, "trowel_" + EnumTrowel.values()[i].getName());
}
}
And here's my ClientProxy register method
#Override
public void registerModelBakeryStuff() {
ModelBakery.registerItemVariants(ModItems.TROWEL, new ResourceLocation(Reference.MOD_ID, "trowel_clear"), new ResourceLocation(Reference.MOD_ID, "trowel_plaster"), new ResourceLocation(Reference.MOD_ID, "trowel_gypsum"));
}
item:0 = trowel_clear (default variant)
item:1 = trowel_plaster (1 variant)
item:2 = trowel_gypsum (2 variant)
There's no any errors in console.
I'm not actually sure what's going wrong, as you've hidden a few things behind other mehods that aren't really in places where they should be (why does ModItems have a registerRender method?)
Anyway, if I dissect my own code1 regarding items with variants I notice two things:
I don't see anything equivalent to variantName + "=" + variant.getByOrdinal(stack.getMetadata())); in your code. This string is what actually maps the metadata to a different model. My variants were all enum specified and hard mapped metadata <-> enum ordinal.
I don't see a call to ModelLoader.setCustomModelResourceLocation() which is what tells the game how to go find a resource for that string.
Its possible that your code does contain those things, but you haven't included it in the question, making it very difficult to figure out where things are going wrong.
Note that the class I've linked here is one half of a system that I custom built to handle the RegistryEvent systems in a way that was more friendly to having transitioned from 1.7.10's GameRegistry system. There's some odd redirections involved shoving data into arrays only to read them back out again later that's not actually necessary if you just construct items in the relevant event (which is the more widely accepted standard). I do all the same things, just at a different point.

Syncing the data in arrays between activities [duplicate]

This question already has answers here:
What's the best way to share data between activities?
(14 answers)
Closed 5 years ago.
I am making a food order app. There is a full page ListView on my main page called MenuActivity and there is a Button when I press it, it will intent to the CartActivity page.
I have arrays food for food name, imgID for food images, butPlus butMinus to adjust the amount of food and amount to keep the amount of each food with an initial value of 0.
I have a method called addAmount , minusAmount in MenuAcitivity that will increase, decrease the amount. It is called by an Adapter of this class.
public static void addAmount(int position) {
amount[position] += 1;
}
Going to CartActivity, I used this to pass all my values.
public void goToCart(MenuItem menuItem) {
Intent in = new Intent(MenuActivity.this, CartActivity.class);
in.putExtra("list", amount);
in.putExtra("imgID", imgID);
in.putExtra("nameList", food);
startActivity(in);
}
to receive the values I created new ArrayList in CartActivity to get the data of the food that the amount in not zero.
// add components to array lists
// addList, removeList are methods to add,remove in my new ArrayList created in this class
for (int i = 0; i < amountList.length; i++) {
if (amountList[i] != 0) {
if (!foodListFinal.contains(foodList[i]))
addList(amountList[i], foodList[i], imgID[i]);
} else if (amountList[i] == 0 && !foodListFinal.isEmpty()) {
if (foodListFinal.contains(foodList[i])) {
index = foodListFinal.indexOf(foodList[i]);
removeList(amountList[index], foodList[index], imgID[index]);
}
}
}
Also, I have a method called addAmount , minusAmount in CartAcitivity that will increase, decrease the amount just like in the MenuActivity. It is called by an Adapter of this class which is not the same one with MenuActivity.
public static void addAmount(int position) {
int newAmount = (amountListFinal.get(position)) + 1;
amountListFinal.set(position, newAmount);
}
public static void minusAmount(int position) {
int newAmount = (amountListFinal.get(position)) - 1;
amountListFinal.set(position, newAmount);
}
Here is my problem..
When I decrease amount in the CartActivity to 0 and I went back to MenuActivity it correctly says 0, but if I switch to CartActivity again the app crashes with an error saying index out of bound.
Please help me with this, or is there any better way to do this please enlighten me. Thank you
for which array caused this error : " saying index out of bound." , foodList or amountList array ? It's gonna help you
I would suggest to use secondary storage to store your changes. Also passing whole array to another activity is not recommended.Use any database to insert change in it and then in cart activity retrieve all data.
This way ,you can achieve same state of amount in various objects.

Clearing a dropdown counter in Java?

I need to clear all the fields in several arrays to re-load a new template to parse. I currently set up a function to clear all the relevant array lists and counts. Those are working fine except I am having a hard time clearing out obrDD inside my clearMicroArray() function.
Here is my current code (without logic to clear obrDD). How can I clear the dropdown information inside my function?
static void clearMicroArray() {
fullMicroArray.clear();
int returnSize = fullMicroArray.size();
System.out.println("size of full array" + returnSize);
obrCount = 0;
fileRowCount = 0;
// obr List
obrList.removeAll(obrList);
obxList.removeAll(obxList);
};
// Populating the OBR number in dropdown
public static void populateOBRDropdown(JComboBox<String> obrDD) {
for (int i = 0; i < fullMicroArray.size(); i++) {
if (fullMicroArray.get(i).substring(0, fullMicroArray.get(i).indexOf("|")).equals("OBR")) {
i++;
obrCount++;
obrDD.addItem("OBR " + obrCount);
}
}
}
obrDD is a JComboBox object that you pass into populateOBRDropdown. Your clearMicroArray method, however, also needs obrDD as an input in order for you to do anything with it. Once you pass a reference to the JComboBox, you can call removeAllItems or removeItem from clearMicroArray.

Android Arraylist find index

I have an ArrayList of object in my Fragment.
ArrayList<MenuListItem> menuItems = new ArrayList<MenuListItem>();
menuItems.add(new MenuListItem("Newsfeed", 20));
menuItems.add(new MenuListItem("FriendsRequest", 1));
menuItems.add(new MenuListItem("Messages", 2));
private class MenuListItem {
public String label;
public int count;
public MenuListItem(String label, int count) {
this.label = label;
this.count = count;
}
}
How can I find the index of object that has the label value "Messages" in my ArrayList from my Activity.
have you try to iterate through elements of menuItems?
something of this sort:
for(MenuListItem menuListItem : menuItems){
if (menuListItem.label.equals(<what you are looking for>){
<do something>
break; // in case when 1st occurence is sufficient
}
}
side note (not related make your members private and add accessors for them)
Edit: just noticed that you are looking for an index, what i have included is to get an MenuListItem what you can do is iterate and return index if you want.
try
String search="Messages";
for(int i=0;i<menuItems.size();i++){
if(menuItems.get(i).label.equalsIgnoreCase(search)){
System.out.println("Index " + i);
break;
}
}
public static int indexOf(final List<MenuListItem> menuItems, final String what) {
final int size = menuItems.size();
for (int i = 0; i < size; i++) {
final String label = menuItems.get(i).label;
if (label != null && label.equals(what)) {
return i;
}
}
return -1;
}
There's a easier and standard way to do this.
Eclipse
Right-click inside MenuListItem class and select Source -> Generate hashCode() and equals() once you are done generating the implementations of these methods. You can use ArrayList.indexOf(Object) to get the index of the item you are looking for.
IntelliJ or Android Studio
Right-click inside your editor and click on Generate and from the dialog that pops up, select hashCode() and equals().
The Collections framework has made things easier for you already. Why not leverage it instead of writing loops to find objects? :)
PS: This can be hand written, but this is something best left to the IDE. Because having too many attributes makes it tricky to get it right the first time.

Having trouble understanding how to maintain state using classes

I'm new to using OOP, I typically just put all my code in a single class and use methods. But I want to maintain state information and think classes are the best fit but I'm having trouble wrapping my head around it.
Say I have a list of items and I want to stop when the total sum of all previous items in the list equals X(in this case 10 so it takes item 1 + 2, then 2+3.etc..until it hits the threshold 10), I can use a method to calculate it but it involves me doing the entire process all over again when all I really need to do is increment by the last item and then see if my data exceeds the threshold. Here's my code so far but I know its not good because although it works its really just using the class as an independent method and recalculating on every loop. My goal is to,using this structure, reduce loops if not necessary to check thresholds.
Any suggestions?
Code:
public class LearningClassesCounter {
public static void main(String[] args) {
int[] list = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] data_list = new int[list.length];
for (int current_location = 0; current_location<list.length;current_location++) {
//can only put commands in here. Nothing above.
Counter checker = new Counter(data_list);
System.out.println(checker.check_data(current_location));
for (int i =0; i<100; i++){
if (checker.check_data(current_location) == false) {
break;
}
data_list[current_location] = (list[current_location]+1); //this is just a random function, it could be any math function I just put it in here to show that some work is being done.
}
}
//its done now lets print the results
for (Integer item : data_list) {
System.out.println(item);
}
}
}
class Counter {
private int[] data_list;
private int total_so_far;
// create a new counter with the given parameters
public Counter(int[] data_list) {
this.data_list = data_list;
this.total_so_far = 0;
}
public boolean check_data(int current_location) {
// TODO Auto-generated method stub
int total_so_far = 0;
//System.out.println(total_so_far);
for (int item : data_list) {
total_so_far = item + total_so_far;
if (total_so_far >= 10) {
break;
}
}
if (total_so_far>=10) {
return false;
} else {
return true;
}
}
}
I don't need anyone to fix my code or anything(I want to do it myself, the code is just to give an idea of what I'm doing). I'm more interested in the flaw in my logic and maybe a way for me to better think about designing classes so I can apply them to my own situations better.
So the solution is that you do not update the data_list directly. Instead have a setter method in the Counter class that takes the index and value to update. It updates the value in the array and also updates a count value.
Something like this:
class Counter{
private final int[] list;
private count = 0;
private final maxCount = 10;
public Counter(int[] list){
this.list = list;
}
public boolean updateValueAndCheckPastMax(int index, int value){
list[index] = value;
count += value;
return count >= maxCount;
}
}
You are way over thinking this, and a counter class is not really necessary in this case.
I'm also interested as to why you'd be doing this line:
data_list[current_location] = (list[current_location]+1);
Do you want your data_list to be the same as list, but each value is incremented by 1?
If you are merely trying to return a sub-array of the values that are < 10, i would suggest just doing this in a for loop, and using an int as a counter.

Categories