Updating the value of arraylist - java

I have a static data inside my arraylist in a controller package. These are my codes in the controller package.
for(int i=0;i<studentPic.length;i++){
//i want to update the value of zero
mStudentModels.add(new StudentModel(studentPic[i],status[i],studentName[i],courseAndYear[i],0));
}
public List<StudentModel> getStudentModels (){
return mStudentModels;
}
Now i want to update a certain data if it meets a certain condition:
private void stopCountdown() {
if (mTask != null) {
mTask.interrupt();
List<StudentModel> studentModels = studentData.getStudentModels();
studentData = new StudentData();
for(int i=0;i<studentModels.size();i++){
StudentModel studentModel = studentModels.get(i);
if(studentModels.get(i).getStatus()=="PRESENT"){
mFirebaseDatabase.child("attendance").child(formattedDate).child("present").push().setValue(studentModel);
}else if(studentModels.get(i).getStatus()=="LATE"){
mFirebaseDatabase.child("attendance").child(formattedDate).child("late").push().setValue(studentModel);
}else{
//i want to update the value of zero here
int absences = studentModel.getNumOfAbsences();
studentModel.setNumOfAbsences(absences+1);
mFirebaseDatabase.child("attendance").child(formattedDate).child("absent").push().setValue(studentModel);
}
}
}
}
The problem is if i call studentData.getStudentModels(); the value always remains zero. Whats the problem with that?
Here's my controller:
public class StudentData {
private List<StudentModel> mStudentModels;
public void setmStudentModels(List<StudentModel> mStudentModels) {
this.mStudentModels = mStudentModels;
}
public StudentData(){
mStudentModels = new ArrayList<>();
int[] studentPic = {R.drawable.boy1, R.drawable.boy2, R.drawable.girl1, R.drawable.girl2, R.drawable.girl3,
R.drawable.girl4, R.drawable.girl5, R.drawable.boy3, R.drawable.girl6, R.drawable.girl7,
R.drawable.boy4, R.drawable.girl8, R.drawable.girl9, R.drawable.girl10, R.drawable.boy5,
R.drawable.girl1, R.drawable.girl12, R.drawable.girl13, R.drawable.boy6, R.drawable.girl14};
String[] status = {"ABSENT","LATE","PRESENT","PRESENT","PRESENT","PRESENT","PRESENT","PRESENT","PRESENT","PRESENT","PRESENT","PRESENT",
"PRESENT","PRESENT","PRESENT","ABSENT","PRESENT","PRESENT","PRESENT","PRESENT"};
String[] studentName = {"Andy Lim", "Benjamin Adams", "Karen Healey", "Anne Pierre", "Corine Alvarez",
"Emily Hedrick", "Courtney Quick", "Oscar Renteria", "Ellen Joy", "Jesse Ramer",
"Jackson Beck", "Alicia Hofer", "Jenae Rupp", "Allison Beitler", "Martin Hofkamp",
"Emma Ruth", "Kathryn Berg", "Michelle Salgado", "Lewis Caskey", "Elizabeth Core"};
String[] courseAndYear = {"BSIT-3", "BSIT 2", "BSIT-3","BSCS-3" , "BSCS-2", "BSIT-3", "BSIT-2", "BSIT-3", "BSIT-2", "BSIT-3",
"BSCS-3", "BSCS-2", "BSCS-3", "BSCS-2", "BSCS-3", "BSIT-3", "BSCS-2", "BSIT-2", "BSCS-3", "BSCS-2"};
for(int i=0;i<studentPic.length;i++){
mStudentModels.add(new StudentModel(studentPic[i],status[i],studentName[i],courseAndYear[i],0));
}
}
public List<StudentModel> getStudentModels (){
return mStudentModels;
}
}
My model looks like this:
public StudentModel(int studentPic, String status, String studentName, String courseAndYear, int numOfAbsences) {
this.studentPic = studentPic;
this.status = status;
this.studentName = studentName;
this.courseAndYear = courseAndYear;
this.numOfAbsences = numOfAbsences;
}

Looks like below checks need to do:
Whether studentPic is not empty.
Whether mStudentModels is not empty (Mainly whether mStudentModels is getting added before the call of stopCountdown() method).
If it does not fix the issue, please provide more information on the code of Controller side.

Related

values of a object stored in a linked list printing but not useable

I am fairly new to java and working on a project to simulate a CPU scheduler in Java and i am using a linked list to store each process object that is read in from a external master list. When I test print the processes and the variables they contain, everything comes out as expected but whenever I try and do something with them it stops working.
public class process
String ID;
int Arrive;
int ExecSize;
int Execstore;
int Tstart;
int Tend;
int quant;
public process(String ID,int Arrive,int ExecSize) {
this.ID = ID;
this.Arrive = Arrive;
this.ExecSize = ExecSize;
this.Execstore=ExecSize;
this.Tend = 0;
this.Tstart = 0;
this.quant = 4;
}
public void setquant(int update) {
this.quant = update;
}
public int getquant() {
return quant;
}
public void setExecSize(int update) {
this.ExecSize = update;
}
public void setTend(int update) {
this.Tend = update;
}
public void setTstart(int update) {
this.Tstart = update;
}
String getID() {
return ID;
}
int getArrive() {
return Arrive;
}
int getExecSize() {
return ExecSize;
}
int getTstart() {
return Tstart;
}
int getTend() {
return Tend;
}
int getExecstore() {
return Execstore;
}
and this is the class used for the simulation
public class fcfs {
int disp;
int Ttotal = 0;
int Exec;
int Turn;
int Wait;
String output;
LinkedList<process> Que = new LinkedList<process>();
LinkedList<process> Quecleared = new LinkedList<process>();
public fcfs(LinkedList<process> B,int D) {
Que.addAll(B);
disp=D;
}
public void run()
{
while (Que != null)
{
Ttotal = Ttotal + disp;
System.out.println(Que.getFirst().getExecSize());
Exec=Que.getFirst().getExecSize();
output += String.format("T%d: %s\n",Ttotal,Que.getFirst().getID());
Que.getFirst().setTstart(Ttotal);
Ttotal = Ttotal+Exec;
Que.getFirst().setTend(Ttotal);
Quecleared.add(Que.poll());
}
}
So whenever i use System.out.println I get the expected result that I read into the list. But anything else I try to do in reference to elements of the process object will not work. Any help would be greatly appreciated
while (!Que.isEmpty())
{
Ttotal = Ttotal + disp;
System.out.println(Que.peekFirst().getExecSize());
Exec=Que.peekFirst().getExecSize();
output += String.format("T%d: %s\n",Ttotal,Que.peekFirst().getID());
Que.peekFirst().setTstart(Ttotal);
Ttotal = Ttotal+Exec;
Que.peekFirst().setTend(Ttotal);
Quecleared.add(Que.pollFirst());
}
This shouldn't throw an error on Exec = Que.peekFirst().getExecSize();
That error is thrown when your container is empty.
EDIT
In your code you specified the condition Que != null. In java once an object has been instantiated it is no longer considered null even if it IS empty. Most likely what was happening here is you continued iterating through your while(Que != null) loop until you had called Que.poll() on all elements of the list.
After clearing the list you did not exit the loop because Que still was not null. Then calling getFirst() on the empty instance of a LinkedList threw an exception.
A similar situation can be seen here with null vs empty strings:
Difference between null and empty ("") Java String
EDIT 2
It also appears that your class methods for getID(), getExecSize(), etc are passing values by reference as opposed to copying their value. Thus any change you make after passing the reference from queue will alter any copies you tried to make of it.
This can be best avoided by creating a new instance of an object and returning that from your function. Shown in an answer on the question linked below:
class Foo {
private Bar myBar;
public Foo deepCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar.clone(); //or new Bar(myBar) or myBar.deepCopy or ...
return newFoo;
}
}
For more information on ways to pass values as opposed to reference values of your pre-existing instances, as well as what a shallow copy actually is, check this link: In Java, what is a shallow copy?

Printing out ObservableList<ObsevableList<String>>items from a tableview one item at a time

I have Board model that I map to a tableView. I can printout the entire selection, but I am trying to print out each line in the selection with special formatting.
Here is the model
public class Board (String pieceno, String avge, String lpte, String lptloc, String grade) {
String PcNo;
String AvgE;
String LptE;
String LptLoc;
String Grade;
public Board( {
this.PcNo = pieceno;
this.AvgE = avge;
this.LptE = lpte;
this.LptLoc = lptloc;
this.Grade = grade;
}
public String getPcNo() {
return PcNo;
}
public void setPcNo(String pcno) {
PcNo = pcno;
}
pubic String getAvgE() {
return AvgE;
}
public void setAvgE(String avge) {
AvgE = avge;
}
public String getLptE() {
return LptE;
}
public void setLptE(String lpte) {
LptE = lpte;
}
public String getLptLoc() {
return LptLoc;
}
public void setLptLoc(String lptloc) {
LptLoc = lptloc;
}
public String getGrade() {
return Grade;
}
public void setGrade(String gr) {
Grade = gr;
}
#Override
public String toString() {
return getPcNo() + "," + getAvgE() + "," + getLptE()
+ "," + getLptLoc() + "," + getGrade() + "\n";
}
}
Now here is the code for tableView and selection of multiple rows.
TableView tableView = new TableView();
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
TableColumn pcNoCol = new TableColumn();
pcNoCol.setText("pcNo");
pcNoCol.setCellValueFactory(new PropertyValueFactory("pcNo"));
tableView.getColumns().add(pcNoCol);
TableColumn avgECol = new TableColumn();
avgECol.setText("avgE");
avgECol.setCellValueFactory(new PropertyValueFactory("avgE"));
tableView.getColumns().add(avgECol);
TableColumn lptECol = new TableColumn();
lptECol.setText("lptE");
lptECol.setCellValueFactory(new PropertyValueFactory("lptE"));
tableView.getColumns().add(lptECol);
TableColumn lptLocCol = new TableColumn();
lptLocCol.setText("lptLoc");
lptLocCol.setCellValueFactory(new PropertyValueFactory("lptLoc"));
tableView.getColumns().add(lptLocCol);
TableColumn gradeCol = new TableColumn();
gradeCol.setText("grade");
gradeCol.setCellValueFactory(new PropertyValueFactory("grade"));
tableView.getColumns().add(gradeCol);
//Bindings.
p.progressProperty().bind(service.progressProperty());
veil.visibleProperty().bind(service.runningProperty());
p.visibleProperty().bind(service.runningProperty());
tableView.itemsProperty().bind(service.valueProperty());
Now the mouse event that grabs the rows and prints out selecteditems is
tableView.setOnMousePressed((MouseEvent event) -> {
ObservableList<ObservableList<String>>selectedItems = tableView.getSelectionModel().getSelectedItems();
//selectedItems.forEach(selecteditem -> System.out.println(selecteditem));
System.out.println(selectedItems);
});
The code works, but Instead of println(selectedItems) I wish to print out each individual selected item, I try the line that is commented out above the foreach line. but I get the following error.
Executing /home/jimbo/NetBeanProjects/AccountFXFrontEnd/dist/run12421/AccountFXFrontEnd.jar usring platform /usr/java/jdk1.8.0_91/jre/bin/java
Exception in thread"JavaFX Application Thread" java.lang.ClassCastException: accountfxfrontend model Board cannot be cast to javafx.collections.ObservableList
at java.lang.Iterable.forEach Iterable.java.75
Can someone tell me what I need to do in order to print out each item rather than the collection? Thanks.
I should be obvious that I am new to javafx and collections I appreciate the help ..
jimbo
You should really start using type parameters, like TableView<Board>. It will help to avoid such mistakes. So, this:
tableView.getSelectionModel().getSelectedItems();
returns ObservableList<Board>, not ObservableList<ObservableList<String>>. Hence the exception when using forEach, as it tries to cast Board to ObservableList. You don't get it with System.out.println(selectedItems), because in this case there is no type casting, println just operates with Object. By the way, if you use:
ObservableList selectedItems = tableView.getSelectionModel().getSelectedItems();
it will work with forEach as well, because, again, it will be operating with Object.

EasyMock: How to Verify Method Order for Set of Values Where Order of Set Does Not Matter

I have a test in which I have a set of specific values for which two different methods will execute once for each value in the set. I need to check that the two methods are called in a specific order in relation to each other, but not in relation to the order of the set of values. For example:
String[] values = { "A", "B", "C" };
for (...<loop over values...) {
methodOne(value);
methodTwo(value);
}
It does not matter which order values is in, but I need to verify that methodOne() and methodTwo() are called for each value in the set AND that methodOne() is always called before methodTwo().
I know that I can create a control and expect methodOne() and methodTwo() for each value, then do control.verify(), but this depends on values being in a specific order.
Is there an elegant way to do this?
Thanks
You can do this using andAnswer().
Basically, inside the andAnswer() from methodOne() you set some variable to hold what the passed in value was.
Then in the andAnswer() for methodTwo() you assert that the same argument matches what you saved from your methodOne answer.
Since each call to methodOne will modify this variable it will make sure methodTwo() is always called after methodOne().
Note this solution is not thread safe
First you need something to hold the variable from the methodOne call. This can be a simple class with a single field or even an array of one element. You need this wrapper object because you need to reference it in the IAnswer which requires a final or effectively final field.
private class CurrentValue{
private String methodOneArg;
}
Now your expectations. Here I called the class that you are testing (The System Under Test) sut:
String[] values = new String[]{"A", "B", "C"};
final CurrentValue currentValue = new CurrentValue();
sut.methodOne(isA(String.class));
expectLastCall().andAnswer(new IAnswer<Void>() {
#Override
public Void answer() throws Throwable {
//save the parameter passed in to our holder object
currentValue.methodOneArg =(String) EasyMock.getCurrentArguments()[0];
return null;
}
}).times(values.length); // do this once for every element in values
sut.methodTwo(isA(String.class));
expectLastCall().andAnswer(new IAnswer<Void>() {
#Override
public Void answer() throws Throwable {
String value =(String) EasyMock.getCurrentArguments()[0];
//check to make sure the parameter matches the
//the most recent call to methodOne()
assertEquals(currentValue.methodOneArg, value);
return null;
}
}).times(values.length); // do this once for every element in values
replay(sut);
... //do your test
verify(sut);
EDIT
you are correct that if you are using EasyMock 2.4 + you can use the new Capture class to get the argument value in a cleaner way for methodOne(). However, you may still need to use the andAnswer() for methodTwo() to make sure the correct values are called in order.
Here is the same code using Capture
Capture<String> captureArg = new Capture<>();
sut.methodOne(and(capture(captureArg), isA(String.class)));
expectLastCall().times(values.length);
sut.methodTwo(isA(String.class));
expectLastCall().andAnswer(new IAnswer<Void>() {
#Override
public Void answer() throws Throwable {
String value =(String) EasyMock.getCurrentArguments()[0];
assertEquals(captureArg.getValue(), value);
return null;
}
}).times(values.length);
replay(sut);
For those interested, I solved this issue using intended EasyMock functionality. The solution was to make a custom IArgumentMatcher to verify against a collection of values and to enforce how many times each value is matched consecutively. The custom matcher, in addition to using strict mocking exactly solves the original problem.
public class SetMatcher implements IArgumentMatcher {
private List<String> valuesToMatch;
private List<String> remainingValues;
private String currentValue = null;
private int timesMatched = 0;
private int setMatches;
public SetMatcher(final List<String> valuesToMatch, final int times) {
this.valuesToMatch = new ArrayList<String>(valuesToMatch);
this.remainingValues = new ArrayList<String>(valuesToMatch);
this.setMatches = times;
}
public String use() {
EasyMock.reportMatcher(this);
return null;
}
public void appendTo(StringBuffer buffer) {
if (this.remainingValues.size() == 0) {
buffer.append("all values in " + this.valuesToMatch + " already matched " + this.setMatches + " time(s)");
} else {
buffer.append("match " + this.valuesToMatch + " " + this.setMatches + " time(s) each");
}
}
public boolean matches(Object other) {
if (this.timesMatched >= this.setMatches) {
this.currentValue = null;
this.timesMatched = 0;
}
if (null == this.currentValue) {
if (this.remainingValues.contains(other)) {
this.currentValue = (String) other;
this.timesMatched = 1;
this.remainingValues.remove(other);
return true;
}
} else if (this.currentValue.equals(other)) {
this.timesMatched++;
return true;
}
return false;
}
}
The class being tested:
public class DataProcessor {
private ServiceOne serviceOne;
private ServiceTwo serviceTwo;
public DataProcessor(ServiceOne serviceOne, ServiceTwo serviceTwo) {
this.serviceOne = serviceOne;
this.serviceTwo = serviceTwo;
}
public void processAll(List<String> allValues) {
List<String> copy = new ArrayList<String>(allValues);
for (String value : copy) {
this.serviceOne.preProcessData(value);
this.serviceTwo.completeTransaction(value);
}
}
}
And the test:
public class DataProcessorTest {
List<String> TEST_VALUES = Arrays.asList("One", "Two", "Three", "Four", "Five");
#Test
public void test() {
IMocksControl control = EasyMock.createStrictControl();
ServiceOne serviceOne = control.createMock(ServiceOne.class);
ServiceTwo serviceTwo = control.createMock(ServiceTwo.class);
SetMatcher matcher = new SetMatcher(TEST_VALUES, 2);
for (int i = 0; i < TEST_VALUES.size(); i++) {
serviceOne.preProcessData(matcher.use());
serviceTwo.completeTransaction(matcher.use());
}
control.replay();
DataProcessor dataProcessor = new DataProcessor(serviceOne, serviceTwo);
dataProcessor.processAll(TEST_VALUES);
control.verify();
}
}
The test will fail for any of the following:
ServiceOne and ServiceTwo are called in the wrong order
ServiceOne and ServiceTwo are not called consecutively with the same value
ServiceOne or ServiceTwo are called with a value that is not in the specified value list
A call is made beyond the number of expected times for a value in the list

ArrayList in class

I have an arraylist of my custom class and for each of those I would like to each keep their own arraylist of computers. Here is my code for the class:
class Services {
public String name;
public String path;
public ArrayList<String> computers = new ArrayList<>();
public Services(String name, String path, String computer) {
this.name = name;
this.path = path;
this.computers.add(computer);
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public void addComputer(String computerName) {
this.computers.add(computerName);
}
}
In my main method I am checking my arraylist of Service for an object with the same name and if it exist then I just want to add that to the arraylist for that object.
However, this is not working and it seems I am just ending up with just one arraylist of all computers not specific to each object of Service.
Here is the section of my main method that uses this class.
stream.iterator().forEachRemaining(x -> {
try {
final boolean[] nextLine = {false};
lines(x.toAbsolutePath(), Charset.forName("UTF-16")).forEach(y -> {
if (!nextLine[0]) {
// Finding Separator
if (y.contains("-----------")) {
//Letting the program know the next line is a service.
nextLine[0] = true;
}
} else {
//Splitting the service name from the path.
String[] service = y.split(" + ");
final boolean[] exists = {false};
String computerName = x.getFileName().toString().substring(0, x.getFileName().toString().length() - 4);
allServices.iterator().forEachRemaining(z -> {
if (z.name.contains(service[0])) {
exists[0] = true;
}
});
if (!exists[0]) {
//Creating new service object if it does not exisit.
//Params are Service name, service path, computer name
Services serviceToAdd = new Services(service[0], service[1], computerName);
//Then adding it to the list to be printed out later.
allServices.add(serviceToAdd);
} else {
//Service name already exists, just adding the computer name to its list of affected computers.
allServices.iterator().forEachRemaining(z -> {
if (z.name.contains(service[0])) {
if (!z.computers.contains(computerName)) {
z.addComputer(computerName);
}
}
});
}
}
}
);
} catch (Exception ex) {
}
});
Ultimately, I am trying to compile a list of services. With that list of services I need to know the name of the service, the path, and which computers have them. I am getting the computer name from the name of the file. It appears that the list of computers for each service is the same list instead of a different list for each service. How do I fix this? Do I need to make a list of lists? That seems redundant and ill performing.
It's pretty hard to tell you what you are missing as you do not provide us the main method which is the most important one relating to your post.
So, with the few info I had, here a little algorithm that would loop over all your stored computers according to the code you posted. That should help you figure out what you are missing, else please post the main method.
public static void main(String args[]) {
String newComputer = "UberPC3000x";
boolean alreadyExistSomeWhere = false;
for (int i = 0; !alreadyExistSomeWhere && i < allMyServices.size(); i++) {
for (int j = 0; !alreadyExistSomeWhere && j < allMyServices.get(i).computers.size(); j++) {
alreadyExistSomeWhere = allMyServices.get(i).computers.get(j).equals(newComputer);
}
}
if (!alreadyExistSomeWhere) //Then it means it was not found and you are free to add wherever you want.
{
}
}

ArrayList of custom Java objects over BlazeDS into AS3.0

Right away i just try to explain my problem:
Using BlazeDS i got the following Javaclasses:
DatabaseService.java:
public class Database {
private Category helpCat = null;
private Category root = new Category(1, "root", null, null);
private List<Article> database;
public Database()
{
// ------------ tree -----------------------------------------------------------------------
List<Category> level_one = new ArrayList<Category>();
List<Category> level_two_computer = new ArrayList<Category>();
List<Category> level_tree_hardware = new ArrayList<Category>();
// Level 1
Category buecher = new Category(2, "buecher", root, null);
Category computer = new Category(3, "computer", root, level_two_computer);
level_one.add(buecher);
level_one.add(computer);
//Level 2
Category hardware = new Category(4, "hardware", computer, level_tree_hardware);
Category software = new Category(5, "software", computer, null);
level_two_computer.add(hardware);
level_two_computer.add(software);
//Level 3
Category graphic = new Category(6, "graphic", hardware, null);
Category sound = new Category(7, "sound", hardware, null);
level_tree_hardware.add(graphic);
level_tree_hardware.add(sound);
// Level 0
root.addChilds(level_one);
// ------ tree end ----------------------------------------------------------------------------
database = new ArrayList<Article>();
try {
add(new Book("Per Anhalter durch die Galaxis", "42", Articletype.BOOK, 795, "Per Anhalter durch die Galaxiss", "Douglas Adams", "Heyne Verlag", "Taschenbuch", "3453146972"), buecher);
add(new Book("Harry Potter und der Stein der Weisen", "descriptionShort", Articletype.BOOK, 1299, "Harry Potter und der Stein der Weisen", "Joanne K. Rowling", "Carlsen Verlag GmbH", "gebunden", "3551551677"), buecher);
add(new Book("Harry Potter und die Kammer des Schreckens", "descriptionShort", Articletype.BOOK, 1499, "Harry Potter und die Kammer des Schreckens", "Joanne K. Rowling", "Carlsen Verlag GmbH", "gebunden", "3551551677"), buecher);
add(new Hardware("nVidia GeForce 8400GS", "Graphikkarte", Articletype.HARDWARE, 2665, "512 GDDR5 Speicher, DVI, 1 GPU", "MSI", "neu"), graphic);
add(new AKW("Biblis C", "Druckwasserreaktor, Preis auf Anfrage, Nur Selbstabholer", Articletype.AKW, -1, "Biblis", 0, 2525, "Siemens", 1, 2012), software);
} catch (Exception e) {
e.printStackTrace();
}
}
public List<Category> getCategories(String node) {
if(node.equalsIgnoreCase("root"))
return root.getChildren();
Category baum = null;
baum = get_node_by_name(root, node);
return baum.getChildren();
}
private Category get_node_by_name(Category localroot, String lookfor)
{
helpCat = null;
if(localroot.getChildren() != null)
{
for (int i = 0; i < localroot.getChildren().size(); ++i)
{
if(!(localroot.getChild(i).getName().equals(lookfor)))
{
get_node_by_name(localroot.getChild(i), lookfor);
}
else
{
helpCat = localroot.getChild(i);
helpCat.setParent(null);
}
}
}
return helpCat;
}
public List<Article> search(int artID, String name, Category categorie){
List<Article> ergebnis = new ArrayList<Article>();
if (artID >= 0)
{
for(int i = 0; i< database.size(); ++i){
if(database.get(i).getID() == artID)
{
ergebnis.add(database.get(i));
return ergebnis;
}
}
}
if (name != null){
for(int i = 0; i<database.size(); ++i){
if (database.get(i).getName().equalsIgnoreCase(name))
ergebnis.add(database.get(i));
}
return ergebnis;
}
if (categorie != null){
{
ergebnis.addAll(categorie.getArticles());
}
return ergebnis;
}
return database;
}
public Article add(Article newArticle, Category cat) throws Exception
{
newArticle.addCategory(cat);
if(newArticle.getID() != 0)
{
throw new Exception("Die Artikel ID wird vom DBS festgelegt!");
}
if (database.isEmpty())
{
newArticle.setID(0);
}
else
{
newArticle.setID(database.get(database.size() - 1).getID()+1);
}
database.add(newArticle);
return newArticle;
}
}
And the Category Class:
public class Category {
private int idCat;
private String nameTEST;
private Category parent = null;
private List<Article> articles = new ArrayList<Article>();
private List<Category> children = new ArrayList<Category>();
public Category(int _id, String _name, Category _parent, List<Category> _children)
{
if(_id > 0)
idCat = _id;
if(_name != null)
nameTEST = _name;
if(_parent != null)
parent = _parent;
if(_children != null)
children = _children;
}
public String toString()
{
return nameTEST;
}
void addArticle(Article article){
articles.add(article);
}
public List<Article> getAllArticles(){
List<Article> ergebnis = this.getArticles();
for (int i = 0; i<children.size();++i){
ergebnis.addAll(children.get(i).getAllArticles());
}
return ergebnis;
}
public void setID(int iD) {
idCat = iD;
}
public int getID() {
return idCat;
}
public void setName(String name) {
this.nameTEST = name;
}
public String getName() {
return nameTEST;
}
/**
* #param parent the parent to set
*/
public void setParent(Category parent)
{
this.parent = parent;
}
/**
* #return the articles
*/
public List<Article> getArticles()
{
return articles;
}
public void addChilds(List<Category> _next)
{
for (int i = 0; i < _next.size(); ++i)
{
children.add(_next.get(i));
}
}
public void addChild(Category one_next)
{
children.add(one_next);
}
public Category getChild(int index)
{
return children.get(index);
}
public void removeChild(Article article){
articles.remove(article);
}
public List<Category> getChildren()
{
return this.children;
}
}
also there are of course classes for articles and so on, but thats not important at that point.
the counterpart in flex looks like this:
Category.as
[RemoteClass(alias="PACKAGE.Category")]
public class Category
{
private var idCat:int = -1;
private var nameTEST:String = null;
private var parent:Category = null;
private var articles:ArrayCollection = new ArrayCollection;
private var children:ArrayCollection = new ArrayCollection;
public function Category(id:int, name:String, parent:Category, childlist:ArrayCollection, articles:ArrayCollection = null)
{
this.idCat = id;
this.nameTEST = name;
this.parent = parent;
this.articles = articles;
this.children = childlist;
}
public function setChildren(childList:ArrayCollection):void
{
this.children = childList;
}
public function getChildren():ArrayCollection
{
return this.children;
}
public function getName():String
{
return this.nameTEST;
}
}
Then i got a Flex service class calling BlazeDS and executing the getCategories java method. Since Flash dosn't seem to understand typed arrays, the result from that method which i get back in flex is a simple array of untyped objects (the mapping dosn't seem to work here, even tought the class category exists in flex and has the same properties).
thats the first thing. but however, i'm converting the untyped objects manually into objects of the category.as class.
the second thing is that categories have child-categories within the java object, which are also ArrayLists of the type category.java. the problem about that: my result event object only contains the first level of categories, looking into them the children are allways null. i dunno why they are empty, since they ARE part of the java object category.
and the third thing (the strangest by fast), you maybe noticed i named the properties of the category.java class strange, like idCat and nameTest instead of simply id and name. why that? because the property names of my flex result objects dont seem to change when i change the java objects properties names (result object properties are named "id" and "name" but the java class object properties are named "idCAT" and "nameTEST"). that it REALLY strange, since if i set the properties, like you see at nameTEST = "TESTNAME" it IS recogniced by flex, only the proertyNAMES dont seem to be recognized at all.
is blaze DS saving / caching the mapping configuration somewhere? how do i get it to rebuild the hole mappings IF so?
that could also explain my problem about the untyped objects i get from java, since before i changed the lists into ArrayLists they where vectors ( which blazeDS dosn't support AFAIK), and maybe not only the propertynames, but also the propertytypes are hard-mapped at some wired place and blazeds just dosn't get them refreshed.
i really like checked everything 5 times by now, even redeployed blazeds on the server to make sure no mappings left, but it didnt help at all.
ANY ideas what i could do? (exept changing to another serializer then blazeds (thats what i'm going to do if everything else fails...))
i have the same issues, but if you can warm up the tree before call the method, it will be ok.
what i mean "warm up" is you iterator the arraylist without doing anything. it is flunky why this work!
I have had similar problems with a list returned from a service not including the child elements in the list. I have found that BlazeDS can return a typed list. The two things that fixed this for me were:
a) Ensure that the returned list is of type java.util.List (not java.util.ArrayList for example).
b) Ensure that the class for the elements in the list have both public setters and getters for all entities to be returned.
For example - the following code works for me:
public class OrganisationService {
...
public List<Organisation> getOrganisations() {
List<Organisation> list = new ArrayList<Organisation>();
...
return list;
}
...
}
As mentioned elsewhere, you need to initiailize your AS3 remote objects so that it is included in the SWF during compilation.
Somewhere in your code, add:
var cat:Category = new Category();
var art:Article = new Article();
That should fix your generic object issue. (I add mine all in one spot, in an application start up method).
It turns out that a simple missmatch of the classnames was the cause of all evil. still some problems to solve, but atleast i get sub-arrays returned now, only the objects are still simple AS 3 objects and not the specified "Category" and "Article" objects, but i think thats because i dont have all methods included and mapping is failing because of that.
but thanks for your offer, i appreciate that.

Categories

Resources