How to set parameter List in retrofit2 - java

I get problem about set parameter in retrofit2
I would like to set group_id and user_id
public class ChatRequest {
private String group_id;
private List<Userbean> users;
public String getGroup_id() {
return group_id;
}
public void setGroup_id(String group_id) {
this.group_id = group_id;
}
public List<Userbean> getUsers() {
return users;
}
public void setUsers(List<Userbean> users) {
this.users = users;
}
public static class Userbean {
private int user_id;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
}
}
and my retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
ChatRequest chatRequest = new ChatRequest();
chatRequest.setGroup_id("dsdfjlds9u");
chatRequest.setUsers ///// How to set user_id = 8(int)
How to set user_id = 8 ??
I have no idea to set it
thanks for your help!

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
ChatRequest chatRequest = new ChatRequest();
chatRequest.setGroup_id("dsdfjlds9u");
UserBean userBean = new UserBean();
userBean.setUser_Id(8);
chatRequest.setUsers(Collections.singletonList(userBean));

Steps Need to follow to set user_id
* Need to initialize a object for ChatRequest
* Declare the list which contains Userbean class as params
* Initialize the Userbean class's object
* Set the user id as 8 using setter class
* Add the user to Userbean list
* Set the Userbean list to ChatRequest
int user_id=8;
ChatRequest chatRequest = new ChatRequest();
List<ChatRequest.Userbean> userbeanList =new List<ChatRequest.Userbean>() {
#Override
public int size() {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public boolean contains(Object o) {
return false;
}
#NonNull
#Override
public Iterator<ChatRequest.Userbean> iterator() {
return null;
}
#NonNull
#Override
public Object[] toArray() {
return new Object[0];
}
#NonNull
#Override
public <T> T[] toArray(#NonNull T[] ts) {
return null;
}
#Override
public boolean add(ChatRequest.Userbean userbean) {
return false;
}
#Override
public boolean remove(Object o) {
return false;
}
#Override
public boolean containsAll(#NonNull Collection<?> collection) {
return false;
}
#Override
public boolean addAll(#NonNull Collection<? extends ChatRequest.Userbean> collection) {
return false;
}
#Override
public boolean addAll(int i, #NonNull Collection<? extends ChatRequest.Userbean> collection) {
return false;
}
#Override
public boolean removeAll(#NonNull Collection<?> collection) {
return false;
}
#Override
public boolean retainAll(#NonNull Collection<?> collection) {
return false;
}
#Override
public void clear() {
}
#Override
public ChatRequest.Userbean get(int i) {
return null;
}
#Override
public ChatRequest.Userbean set(int i, ChatRequest.Userbean userbean) {
return null;
}
#Override
public void add(int i, ChatRequest.Userbean userbean) {
}
#Override
public ChatRequest.Userbean remove(int i) {
return null;
}
#Override
public int indexOf(Object o) {
return 0;
}
#Override
public int lastIndexOf(Object o) {
return 0;
}
#Override
public ListIterator<ChatRequest.Userbean> listIterator() {
return null;
}
#NonNull
#Override
public ListIterator<ChatRequest.Userbean> listIterator(int i) {
return null;
}
#NonNull
#Override
public List<ChatRequest.Userbean> subList(int i, int i1) {
return null;
}
};
ChatRequest.Userbean userBean=new ChatRequest.Userbean();
userBean.setUser_id(user_id);
userbeanList.add(userBean);
chatRequest.setUsers(userbeanList);
Log.e("Users",chatRequest.getUsers().toString());
Log.e("Users id",String.valueOf(userBean.getUser_id()));

Related

Inconsistency: Invalid view holder adapter when using FirestorePagingAdapter with custom wrapper

I wrote a wrapper around FirestorePagingAdapter. This works fine most of the times. But there are occasions where this crashes with
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter
I will show you the complete wrapper. Also the last log message I see before the crash is
[Paging adapter] Data loading finished.
I also noticed, when I slowly scroll the list it works fine. Only if I scroll the list fast it crashes eventually.
So here is the code. I cannot figure out where the problem is. Any help is highly appreciated
public abstract class PagingAdapter<T extends RecyclerItem> extends FirestorePagingAdapter<T, RecyclerViewHolder<T, ? extends ViewBinding>> implements Function1<CombinedLoadStates, Unit> {
protected final String TAG = this.getClass().getSimpleName();
private final SnapshotParser<T> mParser;
private SortedList<T> mListItems;
private int mTryCount;
private boolean mReverseFill = false;
private PagingAdapter(#NonNull FirestorePagingOptions<T> options, PagingAdapterCallback<T> callback) {
super(options);
mListItems = new SortedList(RecyclerItem.class, new SortedListAdapterCallback<T>(this) {
#Override
public int compare(T o1, T o2) {
return callback.compare(o1, o2);
}
#Override
public boolean areContentsTheSame(T oldItem, T newItem) {
return callback.areContentsTheSame(oldItem, newItem);
}
#Override
public boolean areItemsTheSame(T item1, T item2) {
return callback.areContentsTheSame(item1, item2);
}
});
mParser = options.getParser();
this.mTryCount = 0;
}
public void setReverseFill(boolean reverseFill) {
this.mReverseFill = reverseFill;
}
#Override
public int getItemViewType(int position) {
return getList().get(position).getRecyclerItemType().getId();
}
public SortedList<T> getList() {
return mListItems;
}
#NonNull
#Override
public RecyclerViewHolder<T, ? extends ViewBinding> onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerViewHolder<T, ? extends ViewBinding> viewHolder = onCreateViewHolder(parent, RecyclerItemType
.get(viewType));
if (viewHolder == null) {
throw new NullPointerException("Your list contains items for that you did not specify a view holder for");
}
return viewHolder;
}
public abstract RecyclerViewHolder<T, ? extends ViewBinding> onCreateViewHolder(#NonNull ViewGroup parent, RecyclerItemType itemType);
#Override
public void onBindViewHolder(RecyclerViewHolder<T, ? extends ViewBinding> holder, int position) {
try {
//and trigger the paging to load around with the correct "position"
super.onBindViewHolder(holder, getPagingPosition(position)); //<--Needed to page the list, be we do not really use it (see below)
} catch (Exception ignore) {
//If this fails, because there are less items in the list, do not crash, this is fine
Log.d(TAG, "onBindViewHolder: ");
}
holder.bind(getList().get(position));
}
protected int getPagingPosition(int requestedPosition) {
return requestedPosition;
}
#Override
protected void onBindViewHolder(#NonNull RecyclerViewHolder<T, ? extends ViewBinding> holder, int position, #NonNull T model) {
//We do not use this method
}
#Override
public int getItemCount() {
return getList().size();
}
#Override
public Unit invoke(CombinedLoadStates states) {
LoadState refresh = states.getRefresh();
LoadState append = states.getAppend();
if (refresh instanceof LoadState.Error || append instanceof LoadState.Error) {
//The previous load (either initial or additional) failed
Log.d(TAG, "[Paging adapter] An error occurred while loading the data");
if (mTryCount < 3) {
mTryCount += 1;
retry();
}
}
if (refresh instanceof LoadState.Loading) {
Log.d(TAG, "[Paging adapter] Loading initial data");
}
if (append instanceof LoadState.Loading) {
Log.d(TAG, "[Paging adapter] Loading more data");
}
if (append instanceof LoadState.NotLoading) {
LoadState.NotLoading notLoading = (LoadState.NotLoading) append;
if (notLoading.getEndOfPaginationReached()) {
Log.d(TAG, "[Paging adapter] No further documents");
mTryCount = 0;
return null;
}
if (refresh instanceof LoadState.NotLoading) {
Log.d(TAG, "[Paging adapter] Data loading finished");
mTryCount = 0;
List<T> items = new ArrayList<>();
if (mReverseFill) {
for (int i = snapshot().size() - 1; i >= 0; i--) {
T currentItem = mParser.parseSnapshot(snapshot().get(i));
if (getList().indexOf(currentItem) == SortedList.INVALID_POSITION)
items.add(currentItem);
}
} else {
for (DocumentSnapshot snapshot : snapshot()) {
T currentItem = mParser.parseSnapshot(snapshot);
if (getList().indexOf(currentItem) == SortedList.INVALID_POSITION)
items.add(currentItem);
}
}
addAll(items);
return null;
}
}
return null;
}
public void addAll(Collection<T> items) {
getList().beginBatchedUpdates();
getList().addAll(items);
getList().endBatchedUpdates();
}
public abstract static class PagingAdapterCallback<T extends RecyclerItem> {
public abstract int compare(T o1, T o2);
public abstract boolean areContentsTheSame(T oldItem, T newItem);
public abstract boolean areItemsTheSame(T item1, T item2);
}
}
Just in case you wonder. These are the other two wrapper:
public abstract class RecyclerViewHolder<T extends RecyclerItem, E extends ViewBinding> extends RecyclerView.ViewHolder {
public final String TAG = this.getClass().getSimpleName();
protected final E b;
private final Context mContext;
protected RecyclerViewHolder(#NonNull E b) {
super(b.getRoot());
this.b = b;
this.mContext = b.getRoot().getContext();
}
public abstract void bind(T item);
protected Context getContext() {
return mContext;
}
protected Context requireContext() {
return getContext();
}
protected String getString(int resId) {
return mContext.getString(resId);
}
protected String getString(int resId, Object... args) {
return mContext.getString(resId, args);
}
}
and
public interface RecyclerItem {
#NonNull
RecyclerItemType getRecyclerItemType();
default void setRecyclerItemType(RecyclerItemType type){
//Does not do anything per default
}
}

Add items to ProtocolStringList

I am trying to add items to a ProtocolStringList.When I use the add function no error is returned,however when I try to print the list I get null as values.
I dont't know what I'm doing wrong.I tried printing the size to but that also prints 0.I can't figure out what to do.Please Help.Thank you.
Here is the code:
public class demo {
public static void main(String args[])
{
ProtocolStringList s=new ProtocolStringList() {
#Override
public List<ByteString> asByteStringList() {
return null;
}
#Override
public int size() {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public boolean contains(Object o) {
return false;
}
#Override
public Iterator<String> iterator() {
return null;
}
#Override
public Object[] toArray() {
return new Object[0];
}
#Override
public <T> T[] toArray(T[] a) {
return null;
}
#Override
public boolean add(String s) {
return false;
}
#Override
public boolean remove(Object o) {
return false;
}
#Override
public boolean containsAll(Collection<?> c) {
return false;
}
#Override
public boolean addAll(Collection<? extends String> c) {
return false;
}
#Override
public boolean addAll(int index, Collection<? extends String> c) {
return false;
}
#Override
public boolean removeAll(Collection<?> c) {
return false;
}
#Override
public boolean retainAll(Collection<?> c) {
return false;
}
#Override
public void clear() {
}
#Override
public String get(int index) {
return null;
}
#Override
public String set(int index, String element) {
return null;
}
#Override
public void add(int index, String element) {
}
#Override
public String remove(int index) {
return null;
}
#Override
public int indexOf(Object o) {
return 0;
}
#Override
public int lastIndexOf(Object o) {
return 0;
}
#Override
public ListIterator<String> listIterator() {
return null;
}
#Override
public ListIterator<String> listIterator(int index) {
return null;
}
#Override
public List<String> subList(int fromIndex, int toIndex) {
return null;
}
};
s.add("a");
s.add("b");
for(int i=0;i<2;i++)
{
System.out.println(s.get(i));//prints null
}
}
}
to add item to your your list in Java you need to use a Builder and build the object.
You have an example on the reference guide:
https://developers.google.com/protocol-buffers/docs/javatutorial
Person john =
Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("jdoe#example.com")
.addPhones(
Person.PhoneNumber.newBuilder()
.setNumber("555-4321")
.setType(Person.PhoneType.HOME))
.build();
In your example, your code should look something like:
s = ProtocolStringList.newBuilder()
.add("a")
.add("b")
.build();
ProtocolStringList is an Interface (like List). You need to instantiate implemented Data Structure to add value or use its functionality.
Example
ProtocolStringList plist = new LazyStringArrayList();
plist.add("E");

TreeView doesn't displays items

I'm trying to set an initial input to a treeview but I must forget something because It does not displays anything.
public class TreeEditor extends OperationDetailsAspectEditor {
private TreeViewer fConditionField;
private BooleanOperator root;
#Override
public void createControl(Composite parent, FormToolkit toolkit) {
createConditionControls(parent, toolkit);
}
private void createConditionControls(final Composite parent, FormToolkit toolkit) {
fConditionField = new TreeViewer(parent);
fConditionField.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 5));
fConditionField.setLabelProvider(new ConditionsLabelProvider());
fConditionField.setContentProvider(new ConditionsContentProvider());
fConditionField.setUseHashlookup(true);
fConditionField.setInput(getInitialTreeConditions());
fConditionField.expandAll();
}
private BooleanOperator getInitialTreeConditions(){
root = new BooleanOperator(Operator.AND);
return root;
}
}
public class ConditionsLabelProvider implements ILabelProvider {
#Override
public void addListener(ILabelProviderListener paramILabelProviderListener) {}
#Override
public void dispose() { }
#Override
public boolean isLabelProperty(Object paramObject, String paramString) {return false;}
#Override
public void removeListener(
ILabelProviderListener paramILabelProviderListener) {}
#Override
public Image getImage(Object paramObject) {return null;}
#Override
public String getText(Object element) {
if(element instanceof Model){
return ((Model) element).getDisplayName();
} else {
throw unknownElement(element);
}
}
protected RuntimeException unknownElement(Object element) {
return new RuntimeException("Unknown type of element in tree of type " + element.getClass().getName());
}
}
public class ConditionsContentProvider implements ITreeContentProvider {
private static Object[] EMPTY_ARRAY = new Object[0];
protected TreeViewer viewer;
#Override
public void dispose() {
}
#Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.viewer = (TreeViewer) viewer;
}
#Override
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
#Override
public Object[] getChildren(Object parentElement) {
if(parentElement instanceof BooleanOperator){
BooleanOperator operator = ((BooleanOperator) parentElement);
return concat(operator.getOperators().toArray(),
operator.getExpresions().toArray());
}
return EMPTY_ARRAY;
}
#Override
public Object getParent(Object element) {
if(element instanceof Model) {
return ((Model)element).getParent();
}
return null;
}
#Override
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
protected Object[] concat(Object[] a, Object[] b) {
int aLen = a.length;
int bLen = b.length;
Object[] c = new Object[aLen + bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
protected Object[] concat(Object[]... arrays) {
Object[] array = arrays[0] != null? arrays[0] : null;
for(int i = 1; i < arrays.length; i++) {
array = concat(arrays[i-1], arrays[i]);
}
return array;
}
}
Models
public abstract class Model {
protected BooleanOperator parent;
protected String displayName;
public String getDisplayName(){ return displayName; }
public void setDisplayName(String displayName){
this.displayName = displayName;
}
public BooleanOperator getParent() { return parent; }
public void setParent(BooleanOperator parent) { this.parent = parent; }
public Model(String displayName) { this.displayName = displayName; }
public Model(){}
}
public class BooleanOperator extends Model {
private Operator operator;
private List<BooleanOperator> operators;
private List<Expression> expressions;
public Operator getOperator() {
return operator;
}
public List<BooleanOperator> getOperators() {
return operators;
}
public List<Expresion> getExpresions() {
return expresions;
}
public BooleanOperator() {
operators = new ArrayList<BooleanOperator>();
expresions = new ArrayList<Expresion>();
}
public BooleanOperator(Operator operator) {
this();
this.operator = operator;
this.displayName = operator.toString();
}
}
The idea is that Tree contains something such as:
AND
|- Attribute_1 == value_1
|- Attribute_2 == value_2
|- OR
|- Attribute_3 == value_3
The nodes are Boolean operators and the leaves are expressions.

Java 8: Observable List - Invalidation Listener nor Change Listener is called in case of property change

I build a custom property and add it to a observable list. But no listener is called if property content is changed. The following code snippets shows you the 'building':
public static final class TestObject {
private final ReadOnlyStringWrapper title = new ReadOnlyStringWrapper();
private final BooleanProperty selected = new SimpleBooleanProperty(false);
public TestObject(String title) {
this.title.set(title);
}
public String getTitle() {
return title.get();
}
public ReadOnlyStringProperty titleProperty() {
return title.getReadOnlyProperty();
}
public boolean getSelected() {
return selected.get();
}
public BooleanProperty selectedProperty() {
return selected;
}
public void setSelected(boolean selected) {
this.selected.set(selected);
}
#Override
public int hashCode() {
return Objects.hash(title.get());
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final TestObject other = (TestObject) obj;
return Objects.equals(this.title.get(), other.title.get());
}
#Override
public String toString() {
return "TestObject{" +
"title=" + title.get() +
", selected=" + selected.get() +
'}';
}
}
This is my POJO class with my internal property values like name and selected.
public static final class TestProperty extends SimpleObjectProperty<TestObject> {
public TestProperty(String name) {
super(new TestObject(name));
init();
}
public TestProperty(TestObject testObject) {
super(testObject);
init();
}
public String getTitle() {
return getValue().getTitle();
}
public void setSelected(boolean selected) {
getValue().setSelected(selected);
}
public boolean getSelected() {
return getValue().getSelected();
}
public BooleanProperty selectedProperty() {
return getValue().selectedProperty();
}
public ReadOnlyStringProperty titleProperty() {
return getValue().titleProperty();
}
#Override
public void set(TestObject testObject) {
super.set(testObject);
init();
}
#Override
public void setValue(TestObject testObject) {
super.setValue(testObject);
init();
}
private void init() {
if (get() == null)
return;
get().titleProperty().addListener((v, o, n) -> fireValueChangedEvent());
get().selectedProperty().addListener((v, o, n) -> {
fireValueChangedEvent();
});
}
}
This is my custom property based on the POJO. All property changes will fire a change event for my custom property.
#Test
public void testSimple() {
final AtomicInteger counter = new AtomicInteger(0);
final TestProperty testProperty = new TestProperty("Test");
testProperty.addListener(observable -> {
System.out.println("New state: " + testProperty.get().toString());
counter.incrementAndGet();
});
testProperty.setSelected(true);
testProperty.setSelected(false);
Assert.assertEquals(2, counter.intValue());
}
In this test you can see that the property change event works fine.
#Test
public void testList() {
final AtomicInteger counter = new AtomicInteger(0);
final ObservableList<TestProperty> observableList = new ObservableListWrapper<>(new ArrayList<>());
observableList.add(new TestProperty("Test 1"));
observableList.add(new TestProperty("Test 2"));
observableList.add(new TestProperty("Test 3"));
observableList.addListener(new ListChangeListener<TestProperty>() {
#Override
public void onChanged(Change<? extends TestProperty> change) {
System.out.println("**************");
}
});
observableList.addListener((Observable observable) -> {
System.out.println("New state: " + ((TestProperty) observable).get().toString());
counter.incrementAndGet();
});
observableList.get(1).setSelected(true);
observableList.get(2).setSelected(true);
observableList.get(1).setSelected(false);
observableList.get(2).setSelected(false);
Assert.assertEquals(4, counter.intValue());
}
But in this code you see that the observable list not called the invalidation listener nor the change listener if a property value has changed in list.
What is wrong?
Thanks.
To create an observable list that will send "list updated" notifications if properties of elements of the list change, you need to create the list with an extractor. The extractor is a Callback that maps each element of the list to an array of Observables. If any of the Observables changes, InvalidationListeners and ListChangeListeners registered with the list will be notified.
So in your testList() method, you can do
final ObservableList<TestProperty> observableList = FXCollections.observableList(
new ArrayList<>(),
(TestProperty tp) -> new Observable[]{tp.selectedProperty()});
If the title were able to change, and you also wanted the list to receive notifications when that happened, you could do that too:
final ObservableList<TestProperty> observableList = FXCollections.observableList(
new ArrayList<>(),
(TestProperty tp) -> new Observable[]{tp.selectedProperty(), tp.titleProperty()});
Note that because the extractor is a Callback (essentially a function), the implementation can be arbitrarily complex (observe one property conditionally based on the value of another, etc).
The following code shows a simple implementation for a observable list with observable values:
public class ObservableValueListWrapper<E extends ObservableValue<E>> extends ObservableListWrapper<E> {
public ObservableValueListWrapper(List<E> list) {
super(list, o -> new Observable[] {o});}}
Or you must create your list with a POJO:
final ObservableList<MyPOJO> list = new ObservableListWrapper<>(new ArrayList(), o -> new Observable[] { new MyPOJOProperty(o) });
Or you use it so:
final ObservableList<MyPOJO> list = new ObservableListWrapper<>(new ArrayList(), o -> { return new Observable[] {
o.value1Property(),
o.value2Property(),
...};});
That is it! Thanks.
The ObservableList isn't notifying the listeners whenever a property contained within the list is modified, it notifies when the list is notified.
This can be seen when you modify your test:
#Test
public void testList() {
final AtomicInteger counter = new AtomicInteger(0);
final ObservableList<TestProperty> observableList = new ObservableListWrapper<>(new ArrayList<>());
observableList.addListener(new ListChangeListener<TestProperty>() {
#Override
public void onChanged(Change<? extends TestProperty> change) {
System.out.println("**************");
counter.incrementAndGet();
}
});
observableList.add(new TestProperty("Test 1"));
observableList.add(new TestProperty("Test 2"));
observableList.add(new TestProperty("Test 3"));
observableList.get(1).setSelected(true);
observableList.get(2).setSelected(true);
observableList.get(1).setSelected(false);
observableList.get(2).setSelected(false);
Assert.assertEquals(3, counter.intValue());
}
EDIT: Added an example ObserverListener decorator which provides the auto registration/deregistration of the ObservableValue change listener as desired by the OP.
/**
* Decorates an {#link ObservableList} and auto-registers the provided
* listener to all new observers, and auto-unregisters listeners when the
* item is removed from the list.
*
* #param <T>
*/
public class ObservableValueList<T extends ObservableValue> implements ObservableList<T> {
private final ObservableList<T> list;
private final ChangeListener<T> valueListener;
public ObservableValueList(ObservableList<T> list, ChangeListener<T> valueListener) {
this.list = list;
//list to existing contents of list
this.list.stream().forEach((item) -> item.addListener(valueListener));
//register listener which will add/remove listner on change to list
this.list.addListener((Change<? extends T> change) -> {
change.getAddedSubList().stream().forEach(
(item) -> item.addListener(valueListener));
change.getRemoved().stream().forEach(
(item) -> item.removeListener(valueListener));
});
this.valueListener = valueListener;
}
/* What follows is all the required delegate methods */
#Override
public int size() {
return list.size();
}
#Override
public boolean isEmpty() {
return list.isEmpty();
}
#Override
public boolean contains(Object o) {
return list.contains(o);
}
#Override
public Iterator<T> iterator() {
return list.iterator();
}
#Override
public Object[] toArray() {
return list.toArray();
}
#Override
public <T> T[] toArray(T[] ts) {
return list.toArray(ts);
}
#Override
public boolean add(T e) {
return list.add(e);
}
#Override
public boolean remove(Object o) {
return list.remove(o);
}
#Override
public boolean containsAll(Collection<?> clctn) {
return list.containsAll(clctn);
}
#Override
public boolean addAll(Collection<? extends T> clctn) {
return list.addAll(clctn);
}
#Override
public boolean addAll(int i, Collection<? extends T> clctn) {
return list.addAll(i, clctn);
}
#Override
public boolean removeAll(Collection<?> clctn) {
return list.removeAll(clctn);
}
#Override
public boolean retainAll(Collection<?> clctn) {
return list.retainAll(clctn);
}
#Override
public void replaceAll(UnaryOperator<T> uo) {
list.replaceAll(uo);
}
#Override
public void sort(Comparator<? super T> cmprtr) {
list.sort(cmprtr);
}
#Override
public void clear() {
list.clear();
}
#Override
public T get(int i) {
return list.get(i);
}
#Override
public T set(int i, T e) {
return list.set(i, e);
}
#Override
public void add(int i, T e) {
list.add(i, e);
}
#Override
public T remove(int i) {
return list.remove(i);
}
#Override
public int indexOf(Object o) {
return list.indexOf(o);
}
#Override
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
#Override
public ListIterator<T> listIterator() {
return list.listIterator();
}
#Override
public ListIterator<T> listIterator(int i) {
return list.listIterator(i);
}
#Override
public List<T> subList(int i, int i1) {
return list.subList(i, i1);
}
#Override
public Spliterator<T> spliterator() {
return list.spliterator();
}
#Override
public void addListener(ListChangeListener<? super T> ll) {
list.addListener(ll);
}
#Override
public void removeListener(ListChangeListener<? super T> ll) {
list.removeListener(ll);
}
#Override
public boolean addAll(T... es) {
return list.addAll(es);
}
#Override
public boolean setAll(T... es) {
return list.setAll(es);
}
#Override
public boolean setAll(Collection<? extends T> clctn) {
return list.setAll(clctn);
}
#Override
public boolean removeAll(T... es) {
return list.removeAll(es);
}
#Override
public boolean retainAll(T... es) {
return list.retainAll(es);
}
#Override
public void remove(int i, int i1) {
list.remove(i, i1);
}
#Override
public FilteredList<T> filtered(Predicate<T> prdct) {
return list.filtered(prdct);
}
#Override
public SortedList<T> sorted(Comparator<T> cmprtr) {
return list.sorted(cmprtr);
}
#Override
public SortedList<T> sorted() {
return list.sorted();
}
#Override
public void addListener(InvalidationListener il) {
list.addListener(il);
}
#Override
public void removeListener(InvalidationListener il) {
list.removeListener(il);
}
}

java jlist - AbstractListModel - fireContentsChanged does not work properly

I have a simple ListModel, that is filterable and is used in a JList...
It uses the following code...
public class FilteredListModel extends AbstractListModel
{
private List<LineData> data = null;
private final ArrayList<Integer> indices = new ArrayList<Integer>();
public FilteredListModel()
{
}
public void setData(List<LineData> data)
{
this.data = data;
doFilter();
}
public void doFilter()
{
int oldSize = indices.size();
indices.clear();
if (data != null)
{
int count = data.size();
for (int i = 0; i < count; i++)
{
IFiltererListObject element = (IFiltererListObject) data.get(i);
if (element.isVisible())
indices.add(i);
}
}
fireContentsChanged(this, 0, getSize() - 1);
if (oldSize > getSize())
fireIntervalRemoved(this, getSize(), oldSize - 1);
}
#Override
public int getSize()
{
return indices.size();
}
#Override
public Object getElementAt(int index)
{
return data.get(indices.get(index));
}
#Override
public void addListDataListener(ListDataListener l)
{
// TODO Auto-generated method stub
//doFilter();
}
#Override
public void removeListDataListener(ListDataListener l)
{
// TODO Auto-generated method stub
//doFilter();
}
}
The strange thing about it is, that it is not working, just if I click for example outside the window, the JList with the ListModel get's correctly updated...
What am I missing here?
The problem is that the addListDataListener and removeListDataListener methods are empty. This means the JList can no longer attach its listener to the model. The call fireContentsChanged will do nothing, as the super class isn't aware of any listeners.
Either do not override those methods, or make sure you call super.addListDataListener as well.
#Robin please DYM???
import java.util.ArrayList;
import javax.swing.AbstractListModel;
import javax.swing.MutableComboBoxModel;
//usage == new JComboBox(new SectionComboBoxModel(new ArrayList());
public class SectionComboBoxModel extends AbstractListModel implements MutableComboBoxModel {
private static final long serialVersionUID = 1L;
private Object selectedItem;
private ArrayList<Object> sections;
public SectionComboBoxModel(ArrayList<Object> arrayList) {
sections = arrayList;
}
#Override
public Object getSelectedItem() {
return selectedItem;
}
#Override
public void setSelectedItem(Object newValue) {
selectedItem = newValue;
}
#Override
public int getSize() {
return sections.size();
}
#Override
public Object getElementAt(int i) {
return sections.get(i);
}
public void setElementAt(Object newValue, int i) {
this.fireContentsChanged(newValue, i, i);
this.sections.set(i, newValue);
}
#Override
public void addElement(Object obj) {
sections.add(obj);
this.fireIntervalAdded(obj, this.getSize() - 1, this.getSize() - 1);
}
#Override
public void removeElement(Object obj) {
this.fireIntervalRemoved(obj, sections.indexOf(obj), sections.indexOf(obj));
sections.remove(obj);
}
#Override
public void insertElementAt(Object obj, int index) {
sections.add(index, obj);
this.fireIntervalAdded(obj, index, index);
}
#Override
public void removeElementAt(int index) {
this.fireIntervalRemoved(sections.get(index), index, index);
sections.remove(index);
}
public void print() {
System.out.println("\nPrinting List");
for (int i = 0; i < this.sections.size(); i++) {
System.out.println(this.sections.get(i));
}
}
public boolean contains(Object o) {
return sections.contains(o);
}
public Object[] toArray() {
return this.sections.toArray();
}
}

Categories

Resources