I am creating a lobby application which will show all groups on a java tableview. Users are able to join groups that have space in them, else they will not be able to join.
I have been able to create this but I would like to be able to colour the row of the groups that have space in them in green and groups that are full will be coloured in red.
I will provide my code for this below. I am getting NullPointerException, which i dont know why. Thanks.
private void visualGroupAvailability() {
boolean isThereSpace;
for (currentGroupsModel o : groupsTable.getItems()) {
TableRow<currentGroupsModel> currentRow = getTableRow(o.getGroupID());
int limit = o.getNumberOfUsers();
isThereSpace = checkSpaceInGroup(o);
if(isThereSpace) {
currentRow.setStyle("-fx-background-color: #" + "388e3c ");
} else {
currentRow.setStyle("-fx-background-color: #" + "ffcdd2 ");
}
}
}
private TableRow<currentGroupsModel> getTableRow(int rowIndex) {
Set<Node> tableRowCell = groupsTable.lookupAll(".table-row-cell");
TableRow<currentGroupsModel> row = null;
for (Node tableRow : tableRowCell) {
TableRow<currentGroupsModel> r = (TableRow<currentGroupsModel>) tableRow;
row = r;
}
return row;
}
public class currentGroupsModel {
String groupName, groupDescription, hostName, groupType;
Integer numberOfUsers, groupID;
public currentGroupsModel(String gName, String gDesc, String hostName, String groupType, Integer numberOfUsers, Integer groupID){
this.groupName = gName;
this.groupDescription = gDesc;
this.hostName = hostName;
this.groupType = groupType;
this.numberOfUsers = numberOfUsers;
this.groupID = groupID;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupDescription() {
return groupDescription;
}
public void setGroupDescription(String groupDescription) {
this.groupDescription = groupDescription;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getGroupType() {
return groupType;
}
public void setGroupType(String groupType) {
this.groupType = groupType;
}
public Integer getNumberOfUsers() {
return numberOfUsers;
}
public void setNumberOfUsers(int numberOfUsers) {
this.numberOfUsers = numberOfUsers;
}
public Integer getGroupID(){
return this.groupID;
}
public void setGroupID(Integer newID){
this.groupID = newID;
}
}
This question cannot really be answered with what you have given us. It is hard looking for a NullPointerException if there is a currentGroupModel we know nothing about and there are constant red hairings. For example why do you store something in limit, you never use it! Why do you pass getTableRow a rowIndex, that you are never using? As far as I get it your getTableRow returns the last TableRow in the table, not a specific one. Please consider fixing those problems first, before eventually providing some code to understand the inner workings of your currentGroupModel.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am trying to create an ArrayList that reads a .csv file, processes the data into an ArrayList, and then print the list out.
My code so far.
The BankRecords class
import java.io.*;
import java.util.*;
public class BankRecords
{
String sex, region, married, save_act, current_act, mortgage, pep;
int children;
double income;
private String id;
private int age;
public BankRecords(String gender, String area, String marriage, String SaveAccount, String CurrentAccount, String HouseBill, String pepp, int minors, double paycheck, String identification, int years)
{
this.sex = gender;
this.region = area;
this.married = marriage;
this.save_act = SaveAccount;
this.current_act = CurrentAccount;
this.mortgage = HouseBill;
this.pep = pepp;
this.children = minors;
this.income = paycheck;
this.id = identification;
this.age = years;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getRegion()
{
return region;
}
public void setRegion(String region)
{
this.region = region;
}
public String getMarried()
{
return married;
}
public void setMarried(String married)
{
this.married = married;
}
public String getSave_act()
{
return save_act;
}
public void setSave_act(String save_act)
{
this.save_act = save_act;
}
public String getCurrent_act()
{
return current_act;
}
public void setCurrent_act(String current_act)
{
this.current_act = current_act;
}
public String getMortgage()
{
return mortgage;
}
public void setMortgage(String mortgage)
{
this.mortgage = mortgage;
}
public String getPep()
{
return pep;
}
public void setPep(String pep)
{
this.pep = pep;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getChildren()
{
return children;
}
public void setChildren(int children)
{
this.children = children;
}
public double getIncome()
{
return income;
}
public void setIncome(double income)
{
this.income = income;
}
}
The Client abstract class
import java.io.*;
import java.util.*;
public abstract class Client
{
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
static BankRecords robjs[] = new BankRecords[600];
public static void readData()
{
try
{
BufferedReader br;
String filepath = "C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv";
br = new BufferedReader(new FileReader (new File(filepath)));
String line;
while ((line = br.readLine()) != null)
{
BankArray.add(Arrays.asList(line.split(",")));
}
}
catch (Exception e)
{
e.printStackTrace();
}
processData();
}
public static void processData()
{
int idx=0;
for (List<String> rowData: BankArray)
{
robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
robjs[idx].setId(rowData.get(0));
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
idx++;
}
printData();
}
public static void printData()
{
System.out.println("ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE");
int final_record = 24;
for (int i = 0; i < final_record; i++)
{
System.out.println(BankArray.get(i) + "\t ");
}
}
}
The BankRecordsTest class (extends Client)
import java.util.*;
import java.io.*;
public class BankRecordsTest extends Client
{
public static void main(String args [])
{
readData();
}
}
The error
And here is the error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at java.util.Arrays$ArrayList.get(Unknown Source)
at Client.processData(Client.java:33)
at Client.readData(Client.java:24)
at BankRecordsTest.main(BankRecordsTest.java:7)
I'm not sure what the index problem is. Do note that if you run the ReadData() and PrintData() functions separately, the code runs fine but the ProcessData() method causes issues.
I think your data is likely not clean and you are making assumptions about the length of your array. The error you are getting stems from this line:
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
Clearly, rowData doesn't have 2 items (or more). This is why you are getting ArrayIndexOutOfBoundsException. So you want to check where your variable was initialized. You quickly realize it comes from
for (List<String> rowData: BankArray)
So then, the following question is where BankArray gets initialized. That happens in 2 places. First of all
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
You are creating an empty list. So far so good. Note that you don't need to (and therefore shouldn't) initialize with a size. Lists are not like arrays insofar as they can easily grow and you don't need to give their size upfront.
The second place is
BankArray.add(Arrays.asList(line.split(",")));
This is likely where the issue comes from. Your row variable contains the results of Arrays.asList(line.split(",")). So the size of that list depends on the number of commas in that string you are reading. If you don't have any commas, then the size will be 1 (the value of the string itself). And that's what leads me to concluding you have a data quality issue.
What you should really do is add a check in your for (List<String> rowData: BankArray) loop. If for instance, you expect 2 fields, you could write something along the lines of:
if (rowData.size()<2){
throw new Exception("hmmm there's been a kerfuffle');
}
HTH
Helper Class
public class HomeScreenChatsHelper implements Comparable {
private String ID;
private String Name;
private String Image;
private String From;
private String Seen;
private String LastMessage;
private String LastMessageTime;
public HomeScreenChatsHelper(){
}
public HomeScreenChatsHelper(String id, String name, String image, String from, String seen, String lastmessage, String lastMessageTime) {
this.ID=id;
this.Name = name;
this.Image = image;
this.From = from;
this.Seen = seen;
this.LastMessage = lastmessage;
this.LastMessageTime = lastMessageTime;
}
public String getID() {
return ID;
}
public void setID(String id) {
ID = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getMessage() {
return LastMessage;
}
public void setMessage(String message) {
LastMessage = message;
}
public String getTime() {
return LastMessageTime;
}
public void setTime(String time) {
LastMessageTime = time;
}
public String getFrom() {
return From;
}
public void setFrom(String from) {
From = from;
}
public String getSeen() {
return Seen;
}
public void setSeen(String seen) {
Seen = seen;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public int compareTo(Object comparestu) {
long compareage= Long.parseLong(((HomeScreenChatsHelper)comparestu).getTime());
long a = Long.parseLong(LastMessageTime);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
}
return Long.compare(a,compareage);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HomeScreenChatsHelper)) return false;
HomeScreenChatsHelper that = (HomeScreenChatsHelper) o;
return getID().equals(that.getID());
}
#Override
public int hashCode() {
return getID().hashCode();
}
Activity
for(HomeScreenChatsHelper str : mChats) {
if (str.getID().equals(ID)) {
mChats.remove(ID);
break;
}
}
There are a ton of tutorials on how to do it and I've spent the past week looking for a solution and I still don't have it. Is there anyway I can remove an whole object by just specifying just the ID? I wont have the values of all the other fields so I just want to remove a particular object by its ID. Also I cant use the clear option because I need the other data. So can someone help me out please?
With the present code nothing happens. No errors but doesn't work
By using java-8 you can filter the list, result will be the List<HomeScreenChatsHelper> that does have HomeScreenChatsHelper with same id
List<HomeScreenChatsHelper> mChats = new ArrayList<>();
//filter
List<HomeScreenChatsHelper> result = mChats.stream()
.filter(str->!str.getId().equals(Id)).
.collect(Collectors.toList());
Or by using Iterator
// Iterator.remove()
Iterator itr = mChats.iterator();
while (itr.hasNext())
{
HomeScreenChatsHelper x = itr.next();
if (x.getId().equals(Id)) }
itr.remove();
}
}
Your question is quite unclear. is mChats a List containing HomeScreenChatsHelper objects?
I assume so. If this is the case, then you can change your foreach loop into the normal loop
//Assuming mChats is List e.g ArrayList
for (int i = 0; mChats.size(); i++){
if (mChats.get(i).getID().equals(ID)) {
mChats.remove(i);
break;
}
}
The easiest way in Java 8 or later is with Collection#removeIf:
mChats.removeIf(str -> str.getID().equals(ID));
By the way, the convention in Java is for fields to begin with a lowercase letter.
I have created a DynamoDB table with following details:
and I'm trying to insert items in my table:
public static void insertItems() {
AmazonDynamoDBClient ddb = UserPreferenceDemoActivity.clientManager
.ddb();
DynamoDBMapper mapper = new DynamoDBMapper(ddb);
try {
UserPreference userPreference = new UserPreference();
userPreference.setNavn("SalonSol");
for (int i = 800; i <= 1600; i = i + 50) {
userPreference.setTid(i);
userPreference.setMandag("Ledig");
userPreference.setTirsdag("Ledig");
userPreference.setOnsdag("Ledig");
userPreference.setTorsdag("Ledig");
userPreference.setFredag("Ledig");
userPreference.setLørdag("Ledig");
userPreference.setSøndag("Ledig");
Log.d(TAG, "Inserting Tid and Dage");
mapper.save(userPreference);
Log.d(TAG, "Tid and Dage inserted");
}
} catch (AmazonServiceException ex) {
Log.e(TAG, "Error inserting users");
UserPreferenceDemoActivity.clientManager
.wipeCredentialsOnAuthError(ex);
}
}
But AWS keeps returning following exception:
AmazonserviceException: The provided key element does not match the schema
Status Code: 400
I'm actually inserting a String value as a Hash Key and int values as range, so I don't really understand why I'm getting this exception.
My definition of UserPreference class:
#DynamoDBTable(tableName = Constants.TEST_TABLE_NAME)
public static class UserPreference {
private String Navn;
private int Tid;
private String Mandag;
private String Tirsdag;
private String Onsdag;
private String Torsdag;
private String Fredag;
private String Lørdag;
private String Søndag;
#DynamoDBHashKey(attributeName = "Navn")
public String getNavn() {
return Navn;
}
public void setNavn(String Navn) {
this.Navn = Navn;
}
#DynamoDBRangeKey(attributeName = "Tid")
public int getTid() {
return Tid;
}
public void setTid(int Tid) {
this.Tid = Tid;
}
#DynamoDBAttribute(attributeName = "Mandag")
public String getMandag() {
return Mandag;
}
public void setMandag(String Mandag) {
this.Mandag = Mandag;
}
#DynamoDBAttribute(attributeName = "Tirsdag")
public String getTirsdag() {
return Tirsdag;
}
public void setTirsdag(String Tirsdag) {
this.Tirsdag = Tirsdag;
}
#DynamoDBAttribute(attributeName = "Onsdag")
public String getOnsdag() {
return Onsdag;
}
public void setOnsdag(String Onsdag) {
this.Onsdag = Onsdag;
}
#DynamoDBAttribute(attributeName = "Torsdag")
public String getTorsdag() {
return Torsdag;
}
public void setTorsdag(String Torsdag) {
this.Torsdag = Torsdag;
}
#DynamoDBAttribute(attributeName = "Fredag")
public String getFredag() {
return Fredag;
}
public void setFredag(String Fredag) {
this.Fredag = Fredag;
}
#DynamoDBAttribute(attributeName = "Lørdag")
public String getLørdag() {
return Lørdag;
}
public void setLørdag(String Lørdag) {
this.Lørdag = Lørdag;
}
#DynamoDBAttribute(attributeName = "Søndag")
public String getSøndag() {
return Søndag;
}
public void setSøndag(String Søndag) {
this.Søndag = Søndag;
}
}
and the table name has following definition in the "Constants" class:
public static final String TEST_TABLE_NAME = "EkstraTable";
I tried to reproduce the problem by copying and pasting your code then change it to write to my own test table. The problem did not occur, I successfully put all items into the table as per your code:
http://i.imgur.com/lIPgn7P.png
I would suggest checking to make sure you have the newest version of the AWS Java SDK, and that the table was created correctly (I created mine through the console to be safe, you can try that if code still doesn't work after upgrading).
I found the issue. I did a huge mistake by importing:
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey
instead of:
com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBRangeKey
for #DynamoDBRangeKey annotation since I'm using Android mobile SDK. I found the issue by downloading and adding the DynamoDBMapper.jar for 2.1.8, and this version shows the
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey
as deprecated.
I have a problem with Hibernate 4.3.0Final that I have been unable to solve. It is puzzling because I am running similar code in several other places which is working fine. The below code is throwing a java.lang.NullPointerException. It is running in a web service in using a NetBeans setup using Glassfish and JavaDB.
The exception is thrown after item.setRoomId(-1);:
characterId, characterFirstName, roomId, k, variables are being passed in from above; I have verified via debugging that they all have values with valid datatypes; also a valid record is in the Items table.
Query itemsQuery = em.createNamedQuery("Items.findByRoomIdByName");
itemsQuery.setParameter("roomId", roomId);
itemsQuery.setParameter("name", itemName);
Items item = null;
if (itemsQuery.getResultList().isEmpty()) {
throw new UnableToIdentifyException("Item does not exist! You cannot get an item that does not exist. Did you already pick it up?");
}
else {
item = (Items) itemsQuery.getSingleResult();
Boolean isStuck = item.getIsUnmovable();
if (isStuck) {
//Item stuck
notifyItemGetViewers(characterId, characterFirstName, roomId, itemName, isStuck);
}
else {
//Pick up item
try {
item.setRoomId(-1);
item.setCharacterId(characterId);
item.setStoreId(-1);
}
catch (Exception e) {
logger.severe("Wrapped Exection Caught: Exception: " + e.toString() + " Error Message: " + e.getMessage());
}
em.persist(item);
em.flush();
notifyItemGetViewers(characterId, characterFirstName, roomId, itemName, isStuck);
}
}
Entity class (Items.java)
package org.tav.mit;
import java.beans.*;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name = "mit_items")
#NamedQueries({
#NamedQuery(name="Items.findByItemId",
query="SELECT i FROM Items i WHERE i.itemId = :itemId"),
#NamedQuery(name="Items.findByRoomIdByName",
query="SELECT i FROM Items i WHERE i.roomId = :roomId AND i.name = :name"),
#NamedQuery(name="Items.findByRoomId",
query="SELECT i FROM Items i WHERE i.roomId = :roomId"),
#NamedQuery(name="Items.findByCharacterId",
query="SELECT i FROM Items i WHERE i.characterId = :characterId"),
#NamedQuery(name="Items.findByStoreId",
query="SELECT i FROM Items i WHERE i.storeId = :storeId"),
#NamedQuery(name="Items.findByName",
query="SELECT i FROM Items i WHERE i.name = :name")
})
public class Items implements Serializable {
public static final String PROP_ITEMID = "itemIdProperty";
public static final String PROP_ROOMID = "roomIdProperty";
public static final String PROP_CHARACTERID = "characterIdProperty";
public static final String PROP_STOREID = "storeIdProperty";
public static final String PROP_NAME = "nameProperty";
public static final String PROP_DESCRIPTION = "descriptionProperty";
public static final String PROP_TYPE = "typeProperty";
public static final String PROP_WORTH = "worthProperty";
public static final String PROP_BODYLOCATION = "bodyLocationProperty";
public static final String PROP_ISUNMOVABLE = "isUnmovableProperty";
public static final String PROP_ACBONUS = "acBonusProperty";
public static final String PROP_USETIMEDELAY = "useTimeDelayProperty";
public static final String PROP_DAMAGEDICE = "damageDiceProperty";
public static final String PROP_DAMAGEDICESIDES = "damageDiceSidesProperty";
public static final String PROP_DAMAGETYPE = "damageTypeProperty";
public static final String PROP_LIGHTPROVIDED = "lightProvidedProperty";
#Id
#GeneratedValue
private Integer itemId;
#Column()
private Integer roomId = -1;
#Column()
private Integer characterId = -1;
#Column()
private Integer storeId = -1;
#Column(length = 128, nullable = false)
private String name;
#Column(length = 2048, nullable = true)
private String description;
#Column()
private Integer type = -1;
#Column()
private Double worth = 0.0;
#Column()
private Integer bodyLocation = -1;
#Column(nullable = false)
private Boolean isUnmovable = false;
#Column()
private Integer acBonus = -1;
#Column()
private Integer useTimeDelay = -1;
#Column()
private Integer damageDice = -1;
#Column()
private Integer damageDiceSides = -1;
#Column()
private Integer damageType = -1;
#Column(nullable = false)
private Boolean lightProvided = false;
#Column(length = 2048)
private PropertyChangeSupport propertySupport;
public Items()
{
propertySupport = new PropertyChangeSupport(this);
}
public int getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
Integer oldValue = this.itemId;
this.itemId = itemId;
propertySupport.firePropertyChange(PROP_ITEMID, oldValue, itemId);
}
public int getRoomId() {
return roomId;
}
public void setRoomId(Integer roomId) {
Integer oldValue = this.roomId;
this.roomId = roomId;
propertySupport.firePropertyChange(PROP_ROOMID, oldValue, roomId);
}
public int getCharacterId() {
return characterId;
}
public void setCharacterId(Integer characterId) {
Integer oldValue = this.characterId;
this.characterId = characterId;
propertySupport.firePropertyChange(PROP_CHARACTERID, oldValue, characterId);
}
public int getStoreId() {
return storeId;
}
public void setStoreId(Integer storeId) {
Integer oldValue = this.storeId;
this.storeId = storeId;
propertySupport.firePropertyChange(PROP_STOREID, oldValue, storeId);
}
public String getName() {
return name;
}
public void setName(String name) {
String oldValue = this.name;
this.name = name;
propertySupport.firePropertyChange(PROP_NAME, oldValue, name);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
String oldValue = this.description;
this.description = description;
propertySupport.firePropertyChange(PROP_DESCRIPTION, oldValue, description);
}
public int getType() {
return type;
}
public void setType(Integer type) {
Integer oldValue = this.type;
this.type = type;
propertySupport.firePropertyChange(PROP_TYPE, oldValue, type);
}
public double getWorth() {
return worth;
}
public void setWorth(double worth) {
double oldValue = this.worth;
this.worth = worth;
propertySupport.firePropertyChange(PROP_WORTH, oldValue, worth);
}
public int getBodyLocation() {
return bodyLocation;
}
public void setBodyLocation(Integer bodyLocation) {
Integer oldValue = this.bodyLocation;
this.bodyLocation = bodyLocation;
propertySupport.firePropertyChange(PROP_BODYLOCATION, oldValue, bodyLocation);
}
public boolean getIsUnmovable() {
return isUnmovable;
}
public void setIsUnmovable(boolean isUnmovable) {
boolean oldValue = this.isUnmovable;
this.isUnmovable = isUnmovable;
propertySupport.firePropertyChange(PROP_ISUNMOVABLE, oldValue, isUnmovable);
}
public int getAcBonus() {
return acBonus;
}
public void setAcBonus(Integer acBonus) {
Integer oldValue = this.acBonus;
this.acBonus = acBonus;
propertySupport.firePropertyChange(PROP_ACBONUS, oldValue, acBonus);
}
public int getUseTimeDelay() {
return useTimeDelay;
}
public void setUseTimeDelay(Integer useTimeDelay) {
Integer oldValue = this.useTimeDelay;
this.useTimeDelay = useTimeDelay;
propertySupport.firePropertyChange(PROP_USETIMEDELAY, oldValue, useTimeDelay);
}
public int getDamageDice() {
return damageDice;
}
public void setDamageDice(Integer damageDice) {
Integer oldValue = this.damageDice;
this.damageDice = damageDice;
propertySupport.firePropertyChange(PROP_DAMAGEDICE, oldValue, damageDice);
}
public int getDamageDiceSides() {
return damageDiceSides;
}
public void setDamageDiceSides(Integer damageDiceSides) {
Integer oldValue = this.damageDiceSides;
this.damageDiceSides = damageDiceSides;
propertySupport.firePropertyChange(PROP_DAMAGEDICESIDES, oldValue, damageDiceSides);
}
public int getDamageType() {
return damageType;
}
public void setDamageType(Integer damageType) {
Integer oldValue = this.damageType;
this.damageType = damageType;
propertySupport.firePropertyChange(PROP_DAMAGETYPE, oldValue, damageType);
}
public boolean getLightProvided() {
return lightProvided;
}
public void setLightProvided(boolean lightProvided) {
boolean oldValue = this.lightProvided;
this.lightProvided = lightProvided;
propertySupport.firePropertyChange(PROP_LIGHTPROVIDED, oldValue, lightProvided);
}
#Override
public int hashCode() {
int hash = 0;
hash += (itemId != -1 ? itemId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Items)) {
return false;
}
Items other = (Items) object;
if ((this.itemId == -1 && other.itemId != -1) || (this.itemId != -1 &&
!((this.itemId) == (other.itemId)))) {
return false;
}
return true;
}
}
THE DATA THAT IS IN THE ITEMS TABLE:
INSERT INTO mit_items (roomid, characterid, storeid, name, description, type, worth, bodylocation, isunmovable, acbonus, useTimeDelay, damageDice, damageDiceSides, damageType, lightprovided) VALUES(1, -1, -1, 'sword', 'plain steel sword', -1, 0.0, -1, false, -1, -1, -1, -1, -1, false);
One interesting thing is that after the exception throws the database shows that the roomId has in fact been set to -1. However the other fields have not been updated. If I reorder the setFields(-1) methods the exception still trigger on the first method. Also, originally the try-catch block was not there. I had to add it in order to see the root cause exception because this method has the #Transactional annotation which wraps the exception in a general RollbackException that does not show the root cause exception.
Thanks, RC that fixed the problem. propertySupport was returning null. Not sure why, it normally has a Long number cast to a String in there. I ended up removing propertySupport from Items.java Entity class which fixed the problem.
I have feeling why it was failing in this case and not others is because I was manually inserting a record in the Items table for testing and I left the propertySupport field null. So apparently if you have propertySupport implemented you cannot update values in a record that has a null propertySupport field, which I guess would only occur if you inserted the data by a means other than the entity bean.
Thanks again RC! – Sam
I have a question about the handling of node properties in an outlineview.
I have three level of nodes, the rootNode, the node and each node may have sub-nodes. Apart from the rootNode, all nodes and subnodes shall have the same (Boolean => checkbox) property. In my outlineview I have two columns, the node(s) column, and a property column with checkboxes.
What I need now is the behaviour, that when I activate the checkbox of a node, all its sub-nodes checkboxes shall be activated as well, when I deactivate the checkbox of a node, all its sub-nodes checkboxes shall be de-activated as well. If I expand the tree to see the sub-nodes, each sub-node may be selected as well.
My current code looks like the following (some parts are found on the internet):
The main api
public class Category {
private String name;
private Boolean x;
public Category() {
this("empty");
}
public Category(String name) {
this.name = name;
}
public Category(String name, Boolean x) {
this.name = name;
this.x = x;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getx() {
return x;
}
public void setx(Boolean x) {
this.x = x;
}
}
My ChildFactory for the nodes (category) looks like
public class CategoryChildrenFactory extends ChildFactory.Detachable<Category> {
/* detachable has no real effect on the current code, used to control
the life cylce */
#Override
protected boolean createKeys(List<Category> toPopulate) {
toPopulate.add(new Category("Cat1", false));
toPopulate.add(new Category("Cat2", false));
toPopulate.add(new Category("Cat3", false));
return true;
}
#Override
protected Node createNodeForKey(Category key) {
AllNode cn = new AllNode(key);
return cn;
}
}
and for the sub-nodes
public class MovieChildrenFactory extends ChildFactory<String>{
Category category;
public MovieChildrenFactory(Category category) {
this.category = category;
}
#Override
protected boolean createKeys(List<String> toPopulate) {
toPopulate.add("m_1");
toPopulate.add("m_2");
toPopulate.add("m_3");
return true;
}
#Override
protected Node createNodeForKey(String key) {
return new AllNode(category, key);
}
}
The nodes creation is put into a single class for both types (nodes, subnodes)
public class AllNode extends AbstractNode {
Category category;
String title;
private Sheet.Set set;
public AllNode(Category category) {
this(category, null);
this.category = category;
set = Sheet.createPropertiesSet();
}
public AllNode(Category category, String title) {
super(Children.LEAF, Lookups.singleton(category));
if (title == null) {
this.setChildren(Children.create(new MovieChildrenFactory(category), true));
}
this.title = title;
set = Sheet.createPropertiesSet();
}
#Override
public String getHtmlDisplayName() {
String name = "";
if (title == null) {
name = category.getName();
} else {
name = title;
}
return name;
}
#Override
protected Sheet createSheet() {
Sheet sheet = Sheet.createDefault();
Category obj = getLookup().lookup(Category.class);
PlotMathProperties pmp = new PlotMathProperties(obj, title);
set.put(pmp.getMyProperty());
sheet.put(set);
return sheet;
}
}
The properties are handled by
public class PlotMathProperties {
private MyProperty myProperty;
private String categoryName;
private String title;
public PlotMathProperties(Category category, String title) {
this.categoryName = category.getName();
this.title= title;
this.myProperty= new MyProperty ();
}
public XProperty getMyProperty () {
return myProperty;
}
public class MyProperty extends PropertySupport.ReadWrite<Boolean> {
private Boolean isMyProp = false;
public MyProperty () {
super("x", Boolean.class, "XPROP", "Is this a coloured or black and white movie");
}
#Override
public Boolean getValue() throws IllegalAccessException, InvocationTargetException {
return isMyProp ;
}
#Override
public void setValue(Boolean val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
isMyProp = val;
if (isMyProp) {
System.out.println("active: " + categoryName + ", " + title);
} else {
System.out.println("de-active: " + categoryName + ", " + title);
}
}
}
}
Together with a TopComponent the outlineview looks nice and works well.
Has anyone an idea how to setup the the behaviour for the check-boxes
regards