Overriding hashCode() method does not allow saving of class properties in Neo4J - neo4j

I am trying to persist the following class in a Neo4J database using spring-data-neo4j version 4.0.0.RELEASE. It is a class named 'GroupCategory' with some fields like name, ownerId etc. It has overwritten the equals and hashcode methods as provided by eclipse framework.
#NodeEntity(label="GroupCategory")
public class GroupCategory implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#GraphId
private Long id;
#Property private String uuid;
#Property private String name;
#Property private String creatorUuid;
#Property private String ownerUuid;
#Property private String profile;
#Property private String status;
#Relationship(type = GroupRelationshipNames.BELONGS_TO, direction = Relationship.INCOMING)
private List<GroupCategoryRelation> groupCategoryRelations = new ArrayList<GroupCategoryRelation>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreatorUuid() {
return creatorUuid;
}
public void setCreatorUuid(String creatorUuid) {
this.creatorUuid = creatorUuid;
}
public String getOwnerUuid() {
return ownerUuid;
}
public void setOwnerUuid(String ownerUuid) {
this.ownerUuid = ownerUuid;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<GroupCategoryRelation> getGroupCategoryRelations() {
return groupCategoryRelations;
}
public void setGroupCategoryRelations(
List<GroupCategoryRelation> groupCategoryRelations) {
this.groupCategoryRelations = groupCategoryRelations;
}
#Override
public String toString() {
return "GroupCategory [id=" + id + ", uuid=" + uuid + ", name=" + name
+ ", creatorUuid=" + creatorUuid + ", ownerUuid=" + ownerUuid
+ ", profile=" + profile + ", status=" + status
+ ", groupCategoryRelations=" + groupCategoryRelations + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((creatorUuid == null) ? 0 : creatorUuid.hashCode());
result = prime
* result
+ ((groupCategoryRelations == null) ? 0
: groupCategoryRelations.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((ownerUuid == null) ? 0 : ownerUuid.hashCode());
result = prime * result + ((profile == null) ? 0 : profile.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GroupCategory other = (GroupCategory) obj;
if (creatorUuid == null) {
if (other.creatorUuid != null)
return false;
} else if (!creatorUuid.equals(other.creatorUuid))
return false;
if (groupCategoryRelations == null) {
if (other.groupCategoryRelations != null)
return false;
} else if (!groupCategoryRelations.equals(other.groupCategoryRelations))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (ownerUuid == null) {
if (other.ownerUuid != null)
return false;
} else if (!ownerUuid.equals(other.ownerUuid))
return false;
if (profile == null) {
if (other.profile != null)
return false;
} else if (!profile.equals(other.profile))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (uuid == null) {
if (other.uuid != null)
return false;
} else if (!uuid.equals(other.uuid))
return false;
return true;
}
}
I have a test case which first saves and later updates some properties of the objects like below. The test case is as follows
#Test
public void changeCategoryName(){
String ownerUuid = "PERSON_0_UUID";
String name = "GROUP_0";
String name1 = "GROUP_1";
GroupCategory groupCategory = new GroupCategory();
groupCategory.setName(name);
groupCategory.setOwnerUuid(ownerUuid);
groupCategory.setProfile(Profile.PRIVATE.name());
GroupCategory savedGroupCategory = groupCategoryService.create(groupCategory);
System.out.println("----------- "+groupCategoryService.findByUuid(savedGroupCategory.getUuid()));
Assert.assertTrue(groupCategoryService.findByUuid(savedGroupCategory.getUuid()).getName().equals(name));
savedGroupCategory.setName(name1);
savedGroupCategory = groupCategoryService.save(savedGroupCategory);
System.out.println("----------- "+groupCategoryService.findByUuid(savedGroupCategory.getUuid()));
Assert.assertTrue(groupCategoryService.findByUuid(savedGroupCategory.getUuid()).getName().equals(name1));
savedGroupCategory.setName(name);
groupCategoryService.save(savedGroupCategory);
System.out.println("----------- "+groupCategoryService.findByUuid(savedGroupCategory.getUuid()));
Assert.assertTrue(groupCategoryService.findByUuid(savedGroupCategory.getUuid()).getName().equals(name));
}
The answer of the three 'printlns' are given below
----------- GroupCategory [id=889, uuid=9f891006-3d89-4665-ae2f-4946d13b74ac, name=GROUP_0, creatorUuid=null, ownerUuid=PERSON_0_UUID, profile=PRIVATE, status=ACTIVE, groupCategoryRelations=[]]
----------- GroupCategory [id=889, uuid=9f891006-3d89-4665-ae2f-4946d13b74ac, name=GROUP_1, creatorUuid=null, ownerUuid=PERSON_0_UUID, profile=PRIVATE, status=ACTIVE, groupCategoryRelations=[]]
----------- GroupCategory [id=889, uuid=9f891006-3d89-4665-ae2f-4946d13b74ac, name=GROUP_1, creatorUuid=null, ownerUuid=PERSON_0_UUID, profile=PRIVATE, status=ACTIVE, groupCategoryRelations=[]]
If the 'name' field is looked at, it canbe observed that the field is saved and updated for the first two cases. But in the third case, while resetting to the previous value of 'Group_0', the name field is not saved.
The last assertion in the test case fails because the saved object retains the previous value of 'Group1'. The three printlns will give the idea.
It so happens, that the transition of the value of name field from Group_0 to Group_1 works but the one from Group_1 back to Group_0 does not. If the value is changed to any other value other than Group_0 from Group_1, then the value gets updated. That is, the save is not working if the value is being changed alternatively
If I remove the hashCode() method from the GroupCategory class, then all seems to work well. Specifically only commenting the hash code for name field does the trick like
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((creatorUuid == null) ? 0 : creatorUuid.hashCode());
result = prime
* result
+ ((groupCategoryRelations == null) ? 0
: groupCategoryRelations.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
//result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((ownerUuid == null) ? 0 : ownerUuid.hashCode());
result = prime * result + ((profile == null) ? 0 : profile.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
return result;
}
But the same problem persits for other fields as well. As for now it seems that, updating values alternatively (value1 to value2, then again to value1) does not seem to work if hashCode() is being overridden in the class

This bug has been fixed, please use version 1.1.6 of neo4j-ogm.
Update
SDN depends on the Neo4j OGM library. SDN 4.0 was released with an older version of Neo4j-OGM that does not contain this bug fix.
You can add this dependency to override the version of Neo4j OGM-
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm</artifactId>
<version>1.1.6</version>
</dependency>

Related

Android MediatorLiveData to combine multiple LiveData results into single LiveData object (In Java)

I am using 2 LiveDatas from separate tables into the repository of my application. I add the two LiveDatas as sources to the CustomMediatorLiveData class which extends MediatorLiveData.
In the onChanged callback of addSource method for each LiveData, I send the values of both the LiveDatas into a method that combines both and returns a single LiveData which is set as the value for the CustomMediatorLiveData object. I am creating an object of this CustomMediatorLiveData in my Repository and passing the two LiveDatas as parameters for the constructor.
This runs and doesn't give any error but it is messing up the data within the LiveData itself.
example: If the date was originally 15th August 2020 then it can be something like 14th August 0001.
CustomMediatorLiveData:
public class CustomMediatorLiveData extends MediatorLiveData<List<Object>> {
private List<Note> notes = Collections.emptyList();
private List<RecurringTask> recurringTasks = Collections.emptyList();
public CustomMediatorLiveData(LiveData<List<Note>> liveNotes, LiveData<List<RecurringTask>> liveRecurringTasks) {
addSource(liveNotes, notes1 -> {
if (notes1 != null) {
this.notes = notes1;
}
setValue(combineData(notes,recurringTasks));
});
addSource(liveRecurringTasks, recurringTasks1 -> {
if (recurringTasks1 != null) {
this.recurringTasks = recurringTasks1;
}
setValue(combineData(notes,recurringTasks));
});
}
// This method adds the 2 lists into one and sorts them based on dates and priority.
private List<Object> combineData(List<Note> notes, List<RecurringTask> recurringTasks) {
List<Object> combinedList = new ArrayList<>();
if (notes != null && !notes.isEmpty())
combinedList.addAll(notes);
if(recurringTasks!=null && !recurringTasks.isEmpty())
combinedList.addAll(recurringTasks);
Collections.sort(combinedList, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
Date d1, d2;
Note n1 = null, n2 = null;
RecurringTask r1 = null, r2 = null;
if (o1 instanceof Note && o2 instanceof Note) {
int hmm = Boolean.compare(((Note) o2).isPriority(), ((Note) o1).isPriority());
if (hmm != 0)
return hmm;
}
if (o1 instanceof Note) {
d1 = ((Note) o1).getEnd_date();
n1 = ((Note) o1);
} else {
d1 = ((RecurringTask) o1).getEnd_date();
r1 = ((RecurringTask) o1);
}
if (o2 instanceof Note) {
d2 = ((Note) o2).getEnd_date();
n2 = ((Note) o2);
} else {
d2 = ((RecurringTask) o2).getEnd_date();
r2 = ((RecurringTask) o2);
}
if (n1 != null) {
if (r2 != null) {
if (n1.isPriority()) {
return -1;
}
}
}
if (n2 != null) {
if (r1 != null) {
if (n2.isPriority()) {
return 1;
}
}
}
long l1 = d1.getTime() - d2.getTime();
if (l1 > 0) {
return 1;
} else if (l1 < 0) {
return -1;
} else {
return 0;
}
}
});
return combinedList;
}
}
Note Repository class:
public class NoteRepository {
private String DB_NAME = "db_task";
Context context;
private RecurringDao recurringDao;
private LiveData<List<RecurringTask>> upcomingRecurringTasks;
private LiveData<List<Note>> upcomingTasks;
private CustomMediatorLiveData customMediatorLiveData;
private NoteDatabase noteDatabase;
public NoteRepository(Context context) {
noteDatabase = NoteDatabase.getInstance(context);
recurringDao = noteDatabase.recurringDao();
upcomingRecurringTasks = recurringDao.getUpcomingRecurringTask();
upcomingTasks = noteDatabase.daoAccess().fetchUpcomingTasks();
this.context = context;
customMediatorLiveData = new CustomMediatorLiveData(upcomingTasks, upcomingRecurringTasks);
}
public LiveData<List<Object>> getCustomMediatorLiveData() {
return customMediatorLiveData;
}
public LiveData<List<RecurringTask>> getUpcomingRecurringTasks() {
return upcomingRecurringTasks;
}
public LiveData<List<Note>> fetchUpcomingTasks() {
return NoteDatabase.getInstance(context).daoAccess().fetchUpcomingTasks();
}
}
I have tried using the MediatorLiveData object and add the two LiveData sources to it in the repository itself and the same issue persists.
What is the correct way to implement this? How to combine 2 LiveDatas into a single LiveData that can be observed.

I have no idea why i have error Exception in thread "main" java.lang.NullPointerException

I tried to use reverseBystack, reverseBylink and remove.. but I don't know why when i use these functions, it has error like this.
Exception in thread "main" java.lang.NullPointerException
at LinkedQueue$Node.access$200(LinkedQueue.java:44)
at LinkedQueue.reverseBylink(LinkedQueue.java:185)
at LinkedQueue.main(LinkedQueue.java:238)
void reverseByStack() - This method reverses the order of the items in the linked list (first
becomes last and last becomes first) using a stack data strucenter code hereture`
• void reverseByLinks() - This method also reverses the order of the items in the linked list.
It should not create a new list or use a stack. It should only reverse the order of the nodes by
modifying the next values for each node in the list.
• int remove(Item item) - This method scans the queue for occurrences of item and removes
them from the queue. It returns the number of items deleted from the queue.
these are what i want to make.
enter code here public class LinkedQueue<Item> implements Iterable<Item> {
private int N; // number of elements on queue
private Node first; // beginning of queue
private Node last; // end of queue
// helper linked list class
private class Node {
private Item item;
private Node next;
}
public LinkedQueue() {
first = null;
last = null;
N = 0;
assert check();
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue
underflow");
return first.item;
}
public void enqueue(Item item) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
assert check();
}
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue
underflow");
Item item = first.item;
first = first.next;
N--;
if (isEmpty()) last = null; // to avoid loitering
assert check();
return item;
}
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
}
private boolean check() {
if (N == 0) {
if (first != null) return false;
if (last != null) return false;
}
else if (N == 1) {
if (first == null || last == null) return false;
if (first != last) return false;
if (first.next != null) return false;
}
else {
if (first == last) return false;
if (first.next == null) return false;
if (last.next != null) return false;
// check internal consistency of instance variable N
int numberOfNodes = 0;
for (Node x = first; x != null; x = x.next) {
numberOfNodes++;
}
if (numberOfNodes != N) return false;
// check internal consistency of instance variable last
Node lastNode = first;
while (lastNode.next != null) {
lastNode = lastNode.next;
}
if (last != lastNode) return false;
}
return true;
}
void reverseBystack(){
Stack<Item> s = new Stack<>();
Item item;
while (s.isEmpty() != true){
item = dequeue();
s.push(item);
}
while(s.isEmpty() != true){
item = s.pop();
enqueue(item);
}
}
void reverseBylink() {
Node prev = null;
Node current = this.first;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
prev.next = current.next;
}
int remove(Item item){
Node cur = first;
Node prev = last;
while(cur != null) {
if(cur.item.equals(item))
System.out.println(cur.item);
}
cur = cur.next;
prev = cur.next;
return 0;
}
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null;
}
public void remove() { throw new
UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
/**
* Unit tests the <tt>LinkedQueue</tt> data type.
*/
public static void main(String[] args) {
LinkedQueue<String> q = new LinkedQueue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) q.reverseBylink();
else if (!q.isEmpty()) StdOut.print(q.dequeue() + " ");
}
StdOut.println("(" + q.size() + " left on queue)");
}
}

Map Reduce Programming: MultiMap overwrites existing key values

I'm doing Join algorithm in MapReduce. In the Map phase, I made joinColumn as key and the tuple as value. In the reduce method, I have keys and values as (columnname, row). In the reduce phase, I need to separate the "row" into two based on which table they belong to.
I used MultiMap to do this. But the MultiMap is overwriting the existing value. To try to overcome this, I override "equals" and "hashcode" but this did not fix the problem.
public void reduce(Text key,Iterable<Text> values,Context context) throws IOException, InterruptedException{
Multimap<String,Table> entry=LinkedListMultimap.create();
for(Text val : values){
String[] row=val.toString().split(",");
Table t = new Table();
t.setTablename(row[0]);
t.setColumns(val);
entry.put(row[0],t);
}
for (String k: entry.keySet()){
System.out.println("Key : "+k);
Collection<Table> rows=entry.get(k);
Iterator<Table> i=rows.iterator();
while(i.hasNext()){
Table t=i.next();
System.out.println(t.getColumns());
}
}
public class Table {
private String tablename;
private Text columns;
public String getTablename() {
return tablename;
}
public void setTablename(String tablename) {
this.tablename = tablename;
}
public Text getColumns() {
return columns;
}
public void setColumns(Text columns) {
this.columns = columns;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((columns == null) ? 0 : columns.hashCode());
result = prime * result
+ ((tablename == null) ? 0 : tablename.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Table other = (Table) obj;
if (columns == null) {
if (other.columns != null)
return false;
} else if (!columns.equals(other.columns))
return false;
if (tablename == null) {
if (other.tablename != null)
return false;
} else if (!tablename.equals(other.tablename))
return false;
return true;
}
}
I'm getting the following output:
Key : S
R, 2, Don, Larson, Newark, 555-3221
R, 2, Don, Larson, Newark, 555-3221
Key : R
R, 2, Don, Larson, Newark, 555-3221
Key : S
R, 3, Sal, Maglite, Nutley, 555-6905
R, 3, Sal, Maglite, Nutley, 555-6905
Key : R
R, 3, Sal, Maglite, Nutley, 555-6905
Key : R
S, 4, 22000, 7000, part1
Key : S
S, 4, 22000, 7000, part1
It is overriding the existing values. Can anyone help me to sort out this problem?
Your problem is that the object returned by iterating over values is reused by the iterator. Instead of just assigning the value in setColumns(), you need to copy it. Something like:
public void setColumns(Text columns) {
this.columns = new Text(columns.toString());
}

Avro (Microsoft) Serialization of derived type members missing

I am evaluating the performance of Microsoft's implementation of Avro, and at first I thought I was getting phenomenal performance until I realized it just wasn't serializing the entire message ;-)
In the following there is a simple hierarchy of messages decorated with [DataContract] (a base and two derived types). All members are decorated with the [DataMember] attribute. I create a serializer from the base message type and serialize a list of derived messages, but it appears to only serialize/deserialize the base class members. All of the derived message members are missing from the result.
Am I missing something? My application will require mixed message types.
FWIW I don't see any strings from the second derived type in the binary file, so I suspect the derived type members aren't being serialized.
Thanks, Greg
class Program
{
[DataContract(Name = "SideType", Namespace = "AvroMessage")]
public enum EventType
{
Unknown = 0,
One = 1,
Two = 2
}
[DataContract(Name = "MessageBase", Namespace = "AvroMessage")]
public class MessageBase
{
[DataMember(Name = "Subtype")]
public string Subtype;
[DataMember(Name = "Timestamp")]
public DateTime Timestamp;
[DataMember(Name = "GroupName")]
public string GroupName;
public override bool Equals(object obj)
{
MessageBase other = obj as MessageBase;
if (other == null) return false;
return Subtype == other.Subtype &&
Timestamp == other.Timestamp &&
GroupName == other.GroupName;
}
}
[DataContract(Name = "SubMessage1", Namespace = "AvroMessage")]
public class SubMessage1 : MessageBase
{
[DataMember(Name = "Volume")]
public int Volume;
[DataMember(Name = "Count")]
public int Count;
[DataMember(Name = "DetectedSide")]
public EventType Event;
public override bool Equals(object obj)
{
SubMessage1 other = obj as SubMessage1;
if (other == null) return false;
return Subtype == other.Subtype &&
Timestamp == other.Timestamp &&
GroupName == other.GroupName &&
Event == other.Event &&
Volume == other.Volume &&
Count == other.Count;
}
}
[DataContract(Name = "SubMessage2", Namespace = "AvroMessage")]
public class SubMessage2 : MessageBase
{
[DataMember(Name = "Name1")]
public string Name1;
[DataMember(Name = "Volume1")]
public int Volume1;
[DataMember(Name = "Name2")]
public string Name2;
[DataMember(Name = "Volume2")]
public int Volume2;
[DataMember(Name = "PriceMove")]
public double PriceMove;
public override bool Equals(object obj)
{
SubMessage2 other = obj as SubMessage2;
if (other == null) return false;
return Subtype == other.Subtype &&
Timestamp == other.Timestamp &&
GroupName == other.GroupName &&
Volume1 == other.Volume1 &&
Name1 == other.Name1 &&
Volume2 == other.Volume2 &&
Name2 == other.Name2 &&
PriceMove == other.PriceMove;
}
}
public class MessageFactory
{
public static IEnumerable<MessageBase> CreateMessages(int number)
{
Random ran = new Random();
List<MessageBase> retval = new List<MessageBase>();
for (int i = 0; i < number; i++)
{
if (ran.Next(2) == 0)
{
SubMessage1 sub1 = new SubMessage1();
sub1.Timestamp = DateTime.Now;
sub1.GroupName = "Group" + DateTime.Now.Millisecond.ToString();
sub1.Subtype = "SubMessag1";
sub1.Volume = ran.Next(10000);
sub1.Count = ran.Next(100);
if (ran.Next(2) == 0)
{
sub1.Event = EventType.One;
}
else
{
sub1.Event = EventType.Two;
}
retval.Add(sub1);
}
else
{
SubMessage2 sub2 = new SubMessage2();
sub2.Timestamp = DateTime.Now;
sub2.GroupName = "Group" + DateTime.Now.Millisecond.ToString();
sub2.Subtype = "SubMessag2";
sub2.Volume1 = ran.Next(1000);
sub2.PriceMove = ran.NextDouble() * 100 - 50;
sub2.Volume2 = ran.Next(1000);
sub2.Name1 = "Contract" + (DateTime.Now.Millisecond + ran.Next(5)).ToString();
sub2.Name2 = "Contract" + DateTime.Now.Millisecond.ToString();
retval.Add(sub2);
}
}
return retval;
}
}
public static void TestAvro(int count)
{
bool correct = false;
long serTicks = 0;
long deserTicks = 0;
Stopwatch sw = new Stopwatch();
sw.Reset();
var serializer = Microsoft.Hadoop.Avro.AvroSerializer.Create<MessageBase>();
MessageBase[] messages = new MessageBase[count];
using (var file = File.Create(#"C:\test_avro.bin"))
{
int i = 0;
foreach (var message in MessageFactory.CreateMessages(count))
{
messages[i++] = message;
sw.Start();
serializer.Serialize(file, message);
sw.Stop();
}
}
serTicks = sw.ElapsedTicks;
sw.Reset();
List<int> badMessages = new List<int>();
using (var file = File.OpenRead(#"C:\test_avro.bin"))
{
for (int i = 0; i < count; i++)
{
sw.Start();
MessageBase message = serializer.Deserialize(file);
sw.Stop();
SubMessage1 m1 = message as SubMessage1;
SubMessage2 m2 = message as SubMessage2;
bool areNull = (m1 == null) && (m2 == null); // Always true
if (!messages[i].Equals(message)) badMessages.Add(i);
}
}
deserTicks = sw.ElapsedTicks;
correct = badMessages.Count == 0;
long size = (new FileInfo(#"C:\test_proto.bin")).Length;
Console.WriteLine(String.Format("Correct: {0}, Time Out: {1}, , Time In: {2}, , Size: {3}", correct, serTicks, deserTicks, size));
}
static void Main(string[] args)
{
TestAvro(10000);
Console.ReadLine();
}
}
My bad - I forgot the KnownType attribute on the base class, one for each derived type. It works if you include the attributes.

Limited ListField items are drawn instead of complete list in Blackberry

I am trying to draw a list of all contacts saved in device. Everything is fine but when I select all contacts, I get only those contacts which are drawn on the screen. In other words, list drawing only those contacts which are visible on screen. To get the remaining contacts I have to scroll the list.
Here is my code:
public class CheckboxListField extends VerticalFieldManager implements ListFieldCallback, FieldChangeListener {
private static Vector selectedContacts ;
private ChecklistData[] mListData = new ChecklistData[] {};
private ListField mListField;
private static Vector mContacts;
private ContactList contactList;
private Enumeration allContacts;
private SendEmail sendEmail;
private boolean isChecked=false;
private BlackBerryContact contactItem;
private VerticalFieldManager _mainVFM = new VerticalFieldManager();
private int i;
private int j=0;
private String emails="";
private ButtonField _inviteButton;
private HorizontalFieldManager selectAllHFM;
private CustomButtonField selectAllButton;
private Bitmap _uncheckBmp;
private Bitmap _checkBmp;
private LabelField selectAllLabel;
private CheckboxField selectAllCheckBox;
private VerticalFieldManager contactListVFM;
private boolean listItemChecked=false;
private StringBuffer rowString;
private boolean getCBoxStatus;
// A class to hold the Strings in the CheckBox and it's checkbox state
// (checked or unchecked).
private class ChecklistData {
private String _stringVal;
private boolean _checked;
private String _telNumber;
ChecklistData(String stringVal, boolean checked) {
_stringVal = stringVal;
_checked = checked;
//_telNumber = telNumber;
}
// Get/set methods.
private String getStringVal() {
return _stringVal;
}
private boolean isChecked() {
return _checked;
}
// Toggle the checked status.
public void toggleChecked() {
_checked = !_checked;
}
}
public CheckboxListField() {
_mainVFM.add(createContactList(isChecked));
add(_mainVFM);
}
public VerticalFieldManager createContactList(boolean checked){
isChecked = checked;
selectedContacts = new Vector();
//INVITE BUTTON
contactListVFM = new VerticalFieldManager();
_inviteButton=new ButtonField("Invite Friend");
_inviteButton.setChangeListener(this);
_inviteButton.setMargin(2,0,10,0);
//SELECT ALL CHECKBOX
selectAllHFM = new HorizontalFieldManager();
_uncheckBmp = Bitmap.getBitmapResource("Uncheck.png");
_checkBmp = Bitmap.getBitmapResource("checked.png");
selectAllButton = new CustomButtonField(29, "", _uncheckBmp, _checkBmp, ButtonField.CONSUME_CLICK);
selectAllButton.setChangeListener(this);
selectAllButton.setMargin(5,5,5,5);
selectAllCheckBox = new CheckboxField("Select All", isChecked){
protected boolean navigationClick(int status,
int time) {
selectedContacts = new Vector();
emails = "";
boolean getCBoxStatus = selectAllCheckBox.getChecked();
if(listItemChecked == false){
if(_mainVFM.getFieldCount()!= 0){
_mainVFM.deleteAll();
_mainVFM.add(createContactList(getCBoxStatus));
}
}
return true;
}
};
selectAllCheckBox.setChangeListener(this);
selectAllLabel = new LabelField("Select All");
selectAllLabel.setMargin(5,5,5,5);
selectAllHFM.add(selectAllCheckBox);
//selectAllHFM.add(selectAllLabel);
// toggle list field item on navigation click
mListField = new ListField() {
protected boolean navigationClick(int status,
int time) {
toggleItem();
return true;
};
};
// set two line row height
//mListField.setRowHeight(getFont().getHeight() * 2);
mListField.setCallback(this);
//contactListVFM.add(new NullField(NullField.FOCUSABLE));
contactListVFM.add(_inviteButton);
contactListVFM.add(selectAllHFM);
contactListVFM.add(new SeparatorField());
contactListVFM.add(mListField);
//LOAD CONTACTS
// load contacts in separate thread
loadContacts.run();
return contactListVFM;
}
protected Runnable loadContacts = new Runnable() {
public void run() {
reloadContactList();
// fill list field control in UI event thread
UiApplication.getUiApplication().invokeLater(
fillList);
}
};
protected Runnable fillList = new Runnable() {
public void run() {
int size = mContacts.size();
mListData = new ChecklistData[size];
for (int i =0; i < mContacts.size() ; i++) {
contactItem = (BlackBerryContact) mContacts
.elementAt(i);
String displayName = getDisplayName(contactItem);
// String telContact = getContact(item);
mListData[i] = new ChecklistData(
displayName, isChecked);
mListField.invalidate(i);
System.out.println(">>>>>>>>>"+mListData[i]);
}
mListField.setSize(size);
//invalidate();
}
};
protected void toggleItem() {
listItemChecked = true ;
selectAllCheckBox.setChecked(false);
listItemChecked =false ;
// Get the index of the selected row.
int index = mListField.getSelectedIndex();
System.out.println("..............."+index);
if (index != -1) {
// Get the ChecklistData for this row.
ChecklistData data = mListData[index];
// Toggle its status.
data.toggleChecked();
mListField.invalidate(index);
}
}
private boolean reloadContactList() {
try {
contactList = (ContactList) PIM
.getInstance()
.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
allContacts = contactList.items();
mContacts = enumToVector(allContacts);
mListField.setSize(mContacts.size());
System.out.println(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,>>>>>>>>>>"+mListField.getSize());
return true;
} catch (PIMException e) {
return false;
}
}
// Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()){
Contact contact = (Contact) allContacts.nextElement();
if(contactList.isSupportedField(Contact.EMAIL)&& (contact.countValues(Contact.EMAIL) > 0)) {
String emailID=contact.getString(Contact.EMAIL, 0);
if(emailID.length() !=0 && emailID != null ){
v.addElement(contact);
}
}
}
return v;
}
public void drawListRow(ListField list,
Graphics graphics, int index, int y, int w) {
rowString = new StringBuffer();
Object obj = this.get(list, index);
if (list.getSelectedIndex() != index) {
graphics.setBackgroundColor(index % 2 == 0 ||index==0 ? Color.WHITE
: Color.LIGHTGRAY);
graphics.clear();
//list.setFocus();
}
BlackBerryContact contact = (BlackBerryContact) mContacts
.elementAt(index);
String email= contact.getString(Contact.EMAIL, 0);
int vecIndex = selectedContacts.indexOf(email);
if (obj != null) {
ChecklistData currentRow = (ChecklistData) obj;
if (currentRow.isChecked()) {
if(vecIndex == -1){
selectedContacts.addElement(email);
}
rowString
.append(Characters.BALLOT_BOX_WITH_CHECK);
} else {
selectedContacts.removeElement(email);
rowString.append(Characters.BALLOT_BOX);
}
// Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
// Draw the text.
}
graphics.drawText(rowString.toString(), 0, y,
0, w);
}
public static String getDisplayName(Contact contact) {
if (contact == null) {
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(
Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " "
+ displayName;
}
return displayName;
}
}
return displayName;
}
// Returns the object at the specified index.
public Object get(ListField list, int index) {
Object result = null;
if (mListData.length > index) {
result = mListData[index];
}
System.out.println(",,,,,,,,,,,,,,,,,,,,,,,"+mListData.length);
return result;
}
// Returns the first occurrence of the given String,
// beginning the search at index, and testing for
// equality using the equals method.
public int indexOfList(ListField list, String p, int s) {
return -1;
}
// Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list) {
return Graphics.getScreenWidth();
// return Display.getWidth();
}
public void fieldChanged(Field field, int context) {
if(field==_inviteButton){
for(int n=0 ; n<selectedContacts.size() ; n++){
emails= emails + selectedContacts.elementAt(n)+",";
}
//}
String mailBody =": "+Jxa.loginUserName+" invited you on NaijaPings app. Please download NaijaPings Android app from here "+"http://appworld.blackberry.com/webstore/content/77264/?lang=en" ;
sendEmail=new SendEmail(mailBody);
sendEmail.Email(emails,Constant.emailSubject);
emails ="" ;
selectedContacts.removeAllElements();
}else if(field == selectAllCheckBox){
selectedContacts = new Vector();
emails = "";
getCBoxStatus = selectAllCheckBox.getChecked();
//selectedContacts.removeAllElements();
if(listItemChecked == false){
if(_mainVFM.getFieldCount()!= 0){
_mainVFM.deleteAll();
_mainVFM.add(createContactList(getCBoxStatus));
}
}
}
}
}
Here ,in drawListRow() , get() method is called only that many times that is number of contacts are visible on the screen. For remaining contact to add, I have to scroll the list.
In drawListRow() method I am adding those contacts into selectedContacts vector and than using those vector to get contact to send a mail. Contacts will be added only when particular list item will be drawn.
So, how I can get all selected contact without scrolling the list?
This is similar to the problem you had in one of your other recent questions. The problem is that drawListRow() is a callback designed to let you draw the rows that need drawing. It's not meant to do anything else, like assembling a list of contacts to email.
The BlackBerry OS tries to be efficient, so it will only ask you to drawListRow() for the rows that are actually visible to the user (on screen). Anything more would be wasteful.
So, if you want to assemble a list of all selected rows, you should do it somewhere else, not in drawListRow().
It looks to me like you can build a list of all currently selected rows by using this code, wherever you want:
public Vector getSelectedContacts() {
selectedContacts.removeAllElements();
for (int i = 0; i < mListData.length; i++) {
Object obj = mListData[i];
if (obj != null) {
BlackBerryContact contact = (BlackBerryContact) mContacts.elementAt(i);
String email = contact.getString(Contact.EMAIL, 0);
int vecIndex = selectedContacts.indexOf(email);
ChecklistData currentRow = (ChecklistData) obj;
if (currentRow.isChecked()) {
if(vecIndex == -1){
selectedContacts.addElement(email);
}
} else {
// this line is probably not actually needed, since we
// call removeAllElements() at the start of this method
selectedContacts.removeElement(email);
}
}
}
return selectedContacts;
}

Resources