Remove List Items and displace the others - java

I have a List of Buttons and I want to delete the first and the second item. Can i move the rest of Buttons in the List so that the third Button is now the first, the 4th the second and so on?
for(int i = 0; i<nleer; i++){
LinearLayout temp = layoutList.get(letzte);
int tempid = nextButtons.get(i).getId();
CharSequence temptext = nextButtons.get(i).getText();
leerButtons.add(new Button(this));
leerButtons.get(i).setOnClickListener(this);
leerButtons.get(i).setEnabled(true);
leerButtons.get(i).setId(tempid);
leerButtons.get(i).setText(temptext);
leerButtons.get(i).setLayoutParams(new LayoutParams(myButtons.get(i).getWidth(), LayoutParams.WRAP_CONTENT));
tempor.addView(leerButtons.get(i));
nextButtons.remove(i);
at the end i remove the Items (often i = 2) and after this loop i want to use the 3rd Item of the List but i don't know how to move them.

If you have a List x, and you do x.remove(0) to remove the first item, the index of the first item remains 0 (all items shift forward one position). It sounds like you're asking for the default list class behavior.

Related

Loop in arraylist

This is my ArrayList:
{10, 20, 30,40, 50, 60, 70, 80, 90, 100....1000}
I want to loop my result on button click.
I want first 5 results in first Button's click.
Then automatically next 5 result likewise.
Is there any way I can do that?
for(int i=0 ;i<5; i++) {
list = array.getJSONObject(i);
fr.add(list.get("contact"));
}
The problem is that I am only getting first 5 not next results.
Thanks for helping.
If you want to remove first N items in an array list every time you call a method from index a to index b,
You can use ArrayList.removeRange(int fromIndex, int toIndex) every time you press that button (But don't iterate this )
or easily use ArrayList.subList(start, end).clear(); for the same task!
Removes from this list all of the elements whose index is between
fromIndex, inclusive, and toIndex, exclusive. Shifts any succeeding
elements to the left (reduces their index). This call shortens the
list by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this
operation has no effect.)
Read document > http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#removeRange%28int,%20int%29
example :
public void removeFistNItemsFromList(){
for(int i=0 ;i<n; i++) {
// add your items or do what ever you want!
}
myArray.subList(0, 4).clear(); // here from 0 to 4th index items will be removed and list will be updated!
System.out.println("MyArrayListNow:"+myArray);
}
output after each click :
Well, you are trying to reading first 5 elements always hence the problem. One option you have read and remove the elements from the arraylist. But a better approach would be to keep a count of mouse click, in which case it is a classic pagination problem, and u can fetch the next 5 elements and you will not lose the data in arraylist.

How to Iterate over entire android listview

I have a listview where user choose how much for each item he wants, so I need to iterate over each row to get the name (Ovo, Presunto, Queijo, etc), the quantity (the number between the "+" and "-" buttons) and the price. This is already working fine, but I have the following problem: If you look at the bottom of the listview you can know that there are more items, in this picture there are 9 items, but there are 15, and if the user scrolls I will can not iterate over the "hidden" items of listview.
Today I have this code, where I try iterate over the elements of listview:
for (int i = 0; i < listView.getCount(); i++) {
v = listView.getChildAt(i);
if(v != null){
value = (TextView) v.findViewById(R.id.edOptionValue);
nome = (TextView) v.findViewById(R.id.tvOptionName);
tvPrice = (TextView) v.findViewById(R.id.tvPrice);
String price = tvPrice.getText().toString();
//more code here
}
}
listView.getCount() gets the correct number of items (15 items), but when i==10 listView.getChildAt(i) is getting null.
Is there some way to iterate over all items of a listview, incluing the "hidden" elements ?
You should not iterate the list views, instead you should keep all that data (price/quantity) in a list and iterate over that if you really need to do that. That list can be used to populate the ListView as well.

Best way to put 20 elements in a coordinate system with neighbouring elements unique

This question is regarding libGDX, but I think it's in fact more Java/algorithm related.
Part of my game includes placing 20 elements out of predefined 30 elements list on a screen (so effectively a coordinate system) in 20 partially-predefined places.
By partially predefined I mean that they are predefined for each screen, but there can be dozens of screens, so they can be as well treated as random.
The elements will be selected randomly, but the elements close to each other must be unique. By close I mean in range of some arbitrary defined distance X. Effectively each place will have around 3 'close neightbours'.
The best way I can think of so far is as follows:
Calculate the distance between all places. If a given distance between A and B is lower than X put two entries in a map - one (A,B) and one (B,A)
Now start filling the places with elements
For each place create a list with all neightbours using the map from point 1 (let's call it N-list)
For each place create a temporary list with all possible (30) elements (let's call it E-list)
Get a random element from E-list
Iterate through N-list. For each place from the list get an element currently there (if there's any). For this a (place, element) map is needed, so it will be filled as the algorithm progresses.
If the found element is equal to the current random element remove this element from E-list and this place from N-list and come back to point 5
Proceed until all places are filled
Step 1 is in fact a separate algorithm, that probably can be tweaked, ex. if we calculated the A->B distance we don't need to calculate B->A, but that needs an additional map to store calculation info, etc.
I would like to know what you think of this way and if you have any ideas for a better one.
Thanks in advance for your answers.
P.S. Perhaps the terms I used could be better chosen, but I'm not a native speaker and I don't know English math terms :-)
Ok, I think I understood your solution and this is what I thought of initially. But I think it can be slightly optimized by eliminating extra pairs and maps (or maybe not :)
First, create a map of locations where key is location position (or the location itself) and value is a list of location's parents who fall within the close range. Yes it will have multiple parents, not children, it is actually the same but parents are more fitting here as we'll see.
ArrayList<Place> place_list; // your list of places here
ArrayList<Element> element_list; // your list of elements here
HashMap<Place,ArrayList<Place>> parent_map = new HashMap<Place,ArrayList<Place>>;
ArrayList<Place> a;
for (int i = 0; i < place_list.size() - 1; i++) {
Place place1 = place_list.get(i);
for (int j = i + 1; j < place_list.size(); j++) {
Place place2 = place_list.get(j);
int dist = getDistance(place1, place2);
if (dist > DISTANCE_THRESHOLD) continue;
// if this place is within range,
// add parent place to its list and put/update it to the map
a = parent_map.get(place2);
if (a == null) a = new ArrayList<Place>();
a.add(place1);
parent_map.put(place2, a);
}
}
Now we have a map of all places that have parents. Next we do the following: if place does not have parents, it can choose any random element freely. If it does have parents, it checks what elements parents own and reduces the available set of elements. After the set was reduced, any random element can be chosen from it.
HashMap<Place,Element> used_place_map = new HashMap<Place,Element>(); // key is place, value is assigned element
ArrayList<Element> tmp_element_list;
for (i = 0; i < place_list.size(); i++) {
Place place = place_list.get(i);
a = parent_map.get(place);
if (a == null) { // this place has no parents, use elements freely
tmp_element_list = element_list;
} else { // if it has parents, they have already registered their elements in used_place_map
tmp_element_list = new ArrayList<Element>();
// create list of available elements, lame
for (j = 0; j < element_list.size(); j++) tmp_element_list.add(element_list.get(j));
// now reduce it, very lame, sorry
for (Place pl : a) {
Element used_element = used_place_map.get(pl);
for (j = 0; j < tmp_element_list.size(); j++) {
if (used_element.equals(tmp_element_list.get(j)) {
tmp_element_list.remove(j);
break;
}
}
}
}
// finally, get the random index on (probably reduced) array
int element_id = Random.nextInt(tmp_element_list.size());
Element element = element_list.get(element_id);
// store our choice as future parent
used_place_map.put(place, element);
}

Switching values in spinner based on values in ArrayList

I have an Array list which is generated dynamically, it has a capacity to store 5 elements in all. Now this arraylist can contain 2,3,4,5,6 as elements at all. Sometimes some of these elements might be missing as it is generated dynamically. I want to switch positions in the Spinner based in the array list on a button click. How do I keep track of which element is displayed and move to next element?
For example in onCreate I detect the first element of the Arraylist if that is 2 I set
spin.setSelectedItem(aList.get(1));
The above sete my selection to 2 in the spinner.
on Button Click I want to switch to the next element in the list - The problem here is that the next element can be present or not I use the following check:
if ((spin.getSelectedItemPosition()) < Integer.valueOf(pages.get(pages.size()-1)))
But now how set Spinner value to the next element in the above if condition?
EDIT
Currently I am doing something like:
int current = spin.getSelectedItemPosition();
int nextPos = (pages.indexOf(String.valueOf(current)))+1;
spin.setSelection(Integer.valueOf(pages.get(nextPos)));
where spin is my spinner and pages is the arraylist I have.
You can simply use current index and use setSelection method like this:
public void showNext(View v){
int nextIndex = sp.getSelectedItemPosition()+1;
if(nextIndex < spItems.size())
{
sp.setSelection(nextIndex);
}
}
If you don't want to use getSelectedItemPosition directly, you can keep a global integer variable, currentIndex, and set it in onItemSelected method of spinner. And use that in button click method.
Hope it helps.

how to use convert model of Jtable

I have a jTable and I want to delete selected rows:
for( int i=0; i<selectedRows.length ; i++){
defaultablemodel.removeRow( selectedRows[i] - i);
int viewRowIndex = jTableMyTable.convertRowIndexToView(i); <<--- convert it here?
}
I searched around and most suggestions whenever delete rows, we should convert row index to view. Is the above correctly implemented?
I hit this problem because after i sorted my rows, i am unable to delete the row sometimes. but after sorting again i am able to delete a row. So i believe I need to use this convertRowIndexToView method.
You should actually be using
convertRowIndexToModel - Maps the index of the row in terms of the view to the underlying TableModel. If the contents of the model are not sorted the model and view indices are the same.
You have your selected rows, which are the selected indices in the view. So you need to convert those indices to the model indices before deleting.
When you use convertRowIndexToView, you're actually doing the opposite, trying to convert the model index to the table index.
" Is the above correctly implemented?"
First thing, when you want to remove rows this way, you should be traversing the indices backwards, from the last row up. The reason is that when you remove a row, the indices change. So you loop should go backwards like
int [] selectedRows = table.getSelectedRows();
for (int i = selectedRows.length - 1; i >= 0; i--) {
int viewIndex = selctedRows[i];
int modelIndex = table.convertRowIndexToModel(viewIndex);
model.removeRow(modelIndex);
}
The point is you want to remove the highest index first and work your way down to the lower indices.

Categories