Blackberry - How if addElement() doesn't work? - object

I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.

First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.

Related

Application in JaveME using RMS

I'm trying write application in Jave ME with RMS. Application stores information about courier's customer.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
public class ClientsApp extends MIDlet implements CommandListener {
// controls
private Display screen = null;
private List menu = null;
private Form addClientForm = null;
private Form showClientForm = null;
private RecordStore clients;
private ByteArrayOutputStream stream = null;
private DataOutputStream out = null;
private byte[] dates;
TextField name = null;
TextField surname = null;
TextField email = null;
TextField phone = null;
DateField date = null;
TextField price = null;
TextField description = null;
// comands
private final Command backCommand;
private final Command mainMenuCommand;
private final Command exitCommand;
private final Command addClientCommand;
public ClientsApp() {
// initializating controls and comands
menu = new List("Lista klientów", Choice.IMPLICIT);
backCommand = new Command("Cofnij", Command.BACK, 0);
mainMenuCommand = new Command("Main", Command.SCREEN, 1);
exitCommand = new Command("Koniec", Command.EXIT, 2);
addClientCommand = new Command("Zapisz", Command.OK, 3);
stream = new ByteArrayOutputStream();
out = new DataOutputStream(stream);
menu.append("Dodaj klienta", null);
menu.append("Przegladaj klientow", null);
menu.append("Usun klienta", null);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
screen = Display.getDisplay(this);
screen.setCurrent(menu);
try {
clients = RecordStore.openRecordStore("clients", false, RecordStore.AUTHMODE_PRIVATE, false);
}
catch(RecordStoreException exc) {
}
menu.addCommand(exitCommand);
menu.setCommandListener(this);
}
public void commandAction(Command cmd, Displayable dsp) {
if(cmd.getCommandType() == Command.EXIT) {
try{
destroyApp(false);
notifyDestroyed();
}
catch(Exception exc) {
exc.printStackTrace();
}
}
else if(cmd.getCommandType() == Command.BACK) {
screen.setCurrent(menu);
}
else if(cmd.getCommandType() == Command.OK) {
try {
out.writeUTF(name.getString());
out.writeUTF(surname.getString());
out.writeUTF(email.getString());
out.writeUTF(phone.getString());
out.writeUTF(date.getDate().toString());
out.writeUTF(price.getString());
out.writeUTF(description.getString());
dates = stream.toByteArray();
clients.addRecord(dates, 0, dates.length);
stream.close();
out.close();
clients.closeRecordStore();
}
catch(Exception exc) {
}
}
else {
List option = (List) screen.getCurrent();
switch(option.getSelectedIndex()) {
case 0 : {
addClients();
break;
}
case 1 : {
showClients();
break;
}
case 2 : {
deleteClients();
break;
}
}
}
}
protected void addClients() {
addClientForm = new Form("Dodaj klienta");
name = new TextField("Imię klienta", "", 10, TextField.ANY);
surname = new TextField("Nazwisko klienta", "", 15, TextField.ANY);
email = new TextField("Email klienta", "", 20, TextField.EMAILADDR);
phone = new TextField("Numer telefonu", "", 12, TextField.PHONENUMBER);
date = new DateField("Data dostarczenia", DateField.DATE);
price = new TextField("Do zapłaty", "", 6, TextField.NUMERIC);
description = new TextField("Uwagi", "", 50, TextField.ANY);
addClientForm.append(name);
addClientForm.append(surname);
addClientForm.append(email);
addClientForm.append(phone);
addClientForm.append(date);
addClientForm.append(price);
addClientForm.append(description);
screen.setCurrent(addClientForm);
addClientForm.addCommand(backCommand);
addClientForm.addCommand(addClientCommand);
addClientForm.setCommandListener(this);
}
protected void showClients() {
TextBox info = new TextBox("Klienci", null, 100, 0);
RecordEnumeration iterator = null;
String str = null;
byte[] temp = null;
try {
iterator = clients.enumerateRecords(null, null, false);
while(iterator.hasNextElement()) {
temp = iterator.nextRecord();
}
for(int i = 0; i < temp.length; i++) {
str += (char) temp[i];
}
System.out.println(str);
clients.closeRecordStore();
}
catch(Exception exc) {
}
info.setString(str);
screen.setCurrent(info);
}
}
Write/read information from RecordStore don't work. I don't have any exception throw. Could somebody help me?
PS Sorry for my bad language.
Are you sure you do not get any exception? Catch blocks are empty...
I see several issues:
Shouldn't you open the record store with createIfNecessary (2nd parameter) set to true?
In ShowClients method, you should use DataInputStream to read items from the record (the byte array 'temp'), the loop over temp is strange. And a check for null 'temp' to avoid NPE when the store is empty is missing too.
On OK command, and also in ShowClients, the store is closed, so next time it will fail with RecordStoreNotOpenException I guess.
I would also consider flushing 'out' stream before calling stream.toByteArray(), although in this case (DataOutputStrea/ByteArrayOutputStream) it is nothing but a good practice..

Some trouble with ComboBox in Ext.net

I have a Page which a FormPanel(there's a ComboBox in it) and a TreePanel(has a default root node) in it and open ViewState.
I set a value to ComboBox in GET.
When i GET the page the TreePanel's Store send a POST request(store read) before FormPane rendered in client,in this POST request the fromdata has no info about FormPane.
in the POST request recover the ComboBox.Value from ViewState,but in ComboBoxBase.LoadPostData() Ext.Net get value from formdata and cover ComboBox.Value without precondition
it's ComboBoxBase.LoadPostData() code
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
if (!this.EmptyText.Equals(text) && text.IsNotEmpty())
{
List<ListItem> items = null;
if (this.SimpleSubmit)
{
var array = state.Split(new char[] { ',' });
items = new List<ListItem>(array.Length);
foreach (var item in array)
{
items.Add(new ListItem(item));
}
}
else if(state.IsNotEmpty())
{
items = ComboBoxBase.ParseSelectedItems(state);
}
bool fireEvent = false;
if (items == null)
{
items = new List<ListItem>
{
new ListItem(text)
};
/*fireEvent = this.SelectedItems.Count > 0;
this.SelectedItems.Clear();
return fireEvent;
*/
}
foreach (var item in items)
{
if (!this.SelectedItems.Contains(item))
{
fireEvent = true;
break;
}
}
this.SelectedItems.Clear();
this.SelectedItems.AddRange(items);
return fireEvent;
}
else
{
if (this.EmptyText.Equals(text) && this.SelectedItems.Count > 0)
{
this.SelectedItems.Clear();
return true;
}
}
return false;
}
Look at Line 5 to 11,why not change like this
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.Value = text;
this.ResumeScripting();
Sample for this question
page file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<ext:ResourceManager ID="ResourceManager1" runat="server" DisableViewState="false"
AjaxViewStateMode="Enabled" ViewStateMode="Enabled"/>
<form id="form1" runat="server">
<ext:Viewport runat="server" ID="VP">
</ext:Viewport>
</form>
</body>
</html>
cs file
public partial class WebFormTest : System.Web.UI.Page
{
protected override void OnInitComplete(EventArgs e)
{
FP = new FormPanel();
FP.ID = "FP";
FP.Title = "FP";
FP.Region = Region.Center;
TF = new TextField();
TF.ID = "TF";
TF.FieldLabel = "TF";
CB = new ComboBox();
CB.ID = "CB";
CB.FieldLabel = "CB";
CB.Items.Clear();
CB.Items.Add(new ListItem("one", "1"));
CB.Items.Add(new ListItem("two", "2"));
Button test = new Button() { ID = "testbtn", Text = "test" };
test.Listeners.Click.Handler = "App.Store2.load()";
FP.TopBar.Add(new Toolbar() { Items = { test } });
FP.Items.Add(TF);
FP.Items.Add(CB);
GP = new GridPanel();
GP.ID = "GP";
GP.Title = "GP";
GP.Region = Region.East;
GP.Listeners.BeforeRender.Handler = "App.Store1.reload()";
BTN = new Button();
BTN.ID = "BTN";
BTN.Text = "click";
BTN.Icon = Icon.ArrowJoin;
BTN.DirectEvents.Click.Event += new ComponentDirectEvent.DirectEventHandler(Click);
TB = new Toolbar();
TB.Items.Add(BTN);
GP.TopBar.Add(TB);
Store1 = new Store();
Store1.ID = "Store1";
Store1.ReadData += new Store.AjaxReadDataEventHandler(WebFormTest_ReadData);
Model1 = new Model();
Model1.ID = "Model1";
Store1.Model.Add(Model1);
GP.Store.Add(Store1);
TP = new TreePanel();
TP.ID = "TP";
TP.Title = "TP";
TP.Region = Region.East;
TP.RootVisible = false;
TP.Root.Add(new Node() { NodeID = "test", Text = "test" });
Store2 = new TreeStore();
Store2.ID = "Store2";
Store2.ReadData += new TreeStoreBase.ReadDataEventHandler(Store2_ReadData);
TP.Store.Add(Store2);
VP.Items.Add(FP);
//VP.Items.Add(GP);
VP.Items.Add(TP);
if (!X.IsAjaxRequest)
{
CB.Value = "2";
TF.Value = "TEXT";
}
base.OnInitComplete(e);
}
FormPanel FP;
TextField TF;
ComboBox CB;
GridPanel GP;
Button BTN;
Toolbar TB;
Store Store1;
Model Model1;
TreePanel TP;
TreeStore Store2;
protected override void CreateChildControls()
{
base.CreateChildControls();
}
void Store2_ReadData(object sender, NodeLoadEventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
//if (!X.IsAjaxRequest)
//{
// this.Store1.DataSource = this.Data;
// this.Store1.DataBind();
//}
}
protected void Refresh(object sender, DirectEventArgs e)
{
}
bool flag = false;
protected void Click(object sender, DirectEventArgs e)
{
GP.GetStore().Reload();
flag = true;
}
protected override void OnPreRender(EventArgs e)
{
if (flag)
{
TF.Value = "asdasd";
}
base.OnPreRender(e);
}
protected void WebFormTest_ReadData(object sender, StoreReadDataEventArgs e)
{
}
private object[] Data
{
get
{
return new object[]
{
new object[] { "3m Co", 71.72, 0.02, 0.03, "9/1 12:00am" },
};
}
}
}
you also can discuss in Ext.net Forums
We committed the change to the SVN trunk. It will go to the next release (v2.3).
The change is similar to your one, but we decided not to change RawValue as well. Thank you for the report and suggested fix.
Fix (ComboBoxBase LoadPostData)
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();

How to sort search dictionary result based on frequency in j2me

This is my dictionary format:
word Frequency
Gone 60
Goes 10
Go 30
So far the system returns words eg starting with 'g' as go30, goes10, gone60 as a list.
(alphabetically). I want to increase the accuracy of the system so that the search result is based on frequency. Words with high frequencies appear first. kindly help.
Here is the Text midlet class that reads the dictionary line by line.
public class Text extends MIDlet {
// Fields
private static final String[] DEFAULT_KEY_CODES = {
// 1
".,?!'\"1-()#/:_",
// 2
"ABC2",
// 3
"DEF3",
// 4
"GHI4",
// 5
"JKL5",
// 6
"MNO6",
// 7
"PQRS7",
// 8
"TUV8",
// 9
"WXYZ9",
};
//Initializing inner Classes
public ComposeText() {
cmdHandler = new CommandHandler();
lineVector = new Vector();
}
//Calling All InitMethods, setting Theme, Show MainForm
public void startApp() {
Display.init(this);
setTheme();
initCmd();
initMainGui();
mainFrm.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
//Initializing all the Commands
public void initCmd() {
exitCmd = new Command("Exit");
selectCmd = new Command("Ok");
cancelCmd = new Command("Cancel");
predCmd = new Command("Prediction");
sendCmd = new Command("Send");
tfPredArea = new TextField();
//check dictionary
try {
readFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//Initiating MainScreen
public void initMainGui() {
mainFrm = new Form("Compose Text");
mainFrm.setLayout(new BorderLayout());
mainFrm.setLayout(new CoordinateLayout(150, 150));
mainFrm.addCommand(exitCmd);
mainFrm.addCommand(predCmd);
mainFrm.addCommand(sendCmd);
mainFrm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == predCmd){
initPredGui();
} else if(ae.getSource() == exitCmd){
destroyApp(true);
notifyDestroyed();
}
}
});
// To : 07xxxxxxxxxx
Dimension d1 = new Dimension(130, 20);
lbTo = new Label("To:");
lbTo.setX(10);
lbTo.setY(10);
tfTo = new TextField();
tfTo.setReplaceMenu(false);
tfTo.setConstraint(TextField.NUMERIC);
tfTo.setInputModeOrder(new String[]{"123"});
tfTo.setMaxSize(13);
tfTo.setX(40);
tfTo.setY(10);
tfTo.setPreferredSize(d1);
//Message : Compose Text
Dimension d2 = new Dimension(135, 135);
lbSms = new Label("Message:");
lbSms.setX(5);
lbSms.setY(40);
tfSms = new TextField();
tfSms.setReplaceMenu(false);
tfSms.setX(40);
tfSms.setY(40);
tfSms.setPreferredSize(d2);
//add stuff
mainFrm.addComponent(lbTo);
mainFrm.addComponent(lbSms);
mainFrm.addComponent(tfTo);
mainFrm.addComponent(tfSms);
}
//Initiating FilterSelection Screen
public void initPredGui() {
predForm = new Form("Prediction on");
predForm.setLayout(new CoordinateLayout(150, 150));
predForm.addCommand(cancelCmd);
predForm.addCommand(selectCmd);
//textfied in prediction form
final Dimension d5 = new Dimension(200, 200);
tfPredArea = new TextField();
tfPredArea.setReplaceMenu(false);
tfPredArea.setX(10);
tfPredArea.setY(10);
tfPredArea.setPreferredSize(d5);
predForm.addComponent(tfPredArea);
final ListModel underlyingModel = new DefaultListModel(lineVector);
// final ListModel underlyingModel = new
DefaultListModel(tree.getAllPrefixMatches(avail));
// this is a list model that can narrow down the underlying model
final SortListModel proxyModel = new SortListModel(underlyingModel);
final List suggestion = new List(proxyModel);
tfPredArea.addDataChangeListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
int len = 0;
int i = 0;
String input = tfPredArea.getText();
len = tfPredArea.getText().length();
//ensure start search character is set for each word
if (!(len == 0)) {
for (i = 0; i < len; i++) {
if (input.charAt(i) == ' ') {
k = i;
}
}
String currentInput = input.substring(k + 1, len);
proxyModel.filter(currentInput);
}
}
});
Dimension d3 = new Dimension(110, 120);
suggestion.setX(80);
suggestion.setY(80);
suggestion.setPreferredSize(d3);
predForm.addComponent(suggestion);
suggestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String string = suggestion.getSelectedItem().toString();
if (tfPredArea.getText().charAt(0) == 0) {
tfPredArea.setText(string);
}
else if (tfPredArea.getText().length() == 0) {
tfPredArea.setText(string);
} else {
tfPredArea.setText(tfPredArea.getText() + string);
}
}
});
predForm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == addCmd) {
newDictionaryFrm.show();
} else {
mainFrm.show();
}
}
});
predForm.show();
}
//Setting Theme for All Forms
public void setTheme() {
try {
Resources r = Resources.open("/theme.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
System.err.println("Couldn't load the theme");
}
}
//Inner class CommandHandler
public class CommandHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
//cancelCommand from predictionForm
if (ae.getSource() == cancelCmd) {
if (edit) {
mainFrm.show();
// clearFields();
} else if (ae.getSource() == selectCmd){
tfPredList.addDataChangeListener(model);
predForm.show();
}
else{}
}
}
}
// method that reads dictionary line by line
public void readFile() throws IOException {
tree = new Trie();
InputStreamReader reader = new InputStreamReader(
getClass().getResourceAsStream("/Maa Corpus.txt-01-ngrams-Alpha.txt"));
String line = null;
// Read a single line from the file. null represents the EOF.
while ((line = readLine(reader)) != null) {
// Append to a vector to be used as a list
lineVector.addElement(line);
}
}
public String readLine(InputStreamReader reader) throws IOException {
// Test whether the end of file has been reached. If so, return null.
int readChar = reader.read();
if (readChar == -1) {
return null;
}
StringBuffer string = new StringBuffer("");
// Read until end of file or new line
while (readChar != -1 && readChar != '\n') {
// Append the read character to the string.
// This is part of the newline character
if (readChar != '\r') {
string.append((char) readChar);
}
// Read the next character
readChar = reader.read();
}
return string.toString();
}
}
}
The SortListModel Class has a filter method that gets prefix from the textfield datachangeLister
class SortListModel implements ListModel, DataChangedListener {
private ListModel underlying;
private Vector filter;
private Vector listeners = new Vector();
public SortListModel(ListModel underlying) {
this.underlying = underlying;
underlying.addDataChangedListener(this);
}
private int getFilterOffset(int index) {
if(filter == null) {
return index;
}
if(filter.size() > index) {
return ((Integer)filter.elementAt(index)).intValue();
}
return -1;
}
private int getUnderlyingOffset(int index) {
if(filter == null) {
return index;
}
return filter.indexOf(new Integer(index));
}
public void filter(String str) {
filter = new Vector();
str = str.toUpperCase();
for(int iter = 0 ; iter < underlying.getSize() ; iter++) {
String element = (String)underlying.getItemAt(iter);
if(element.toUpperCase().startsWith(str)) // suggest only if smthing
{
filter.addElement(new Integer(iter));
}
}
dataChanged(DataChangedListener.CHANGED, -1);
}
public Object getItemAt(int index) {
return underlying.getItemAt(getFilterOffset(index));
}
public int getSize() {
if(filter == null) {
return underlying.getSize();
}
return filter.size();
}
public int getSelectedIndex() {
return Math.max(0, getUnderlyingOffset(underlying.getSelectedIndex()));
}
public void setSelectedIndex(int index) {
underlying.setSelectedIndex(getFilterOffset(index));
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addElement(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeElement(l);
}
public void addSelectionListener(SelectionListener l) {
underlying.addSelectionListener(l);
}
public void removeSelectionListener(SelectionListener l) {
underlying.removeSelectionListener(l);
}
public void addItem(Object item) {
underlying.addItem(item);
}
public void removeItem(int index) {
underlying.removeItem(index);
}
public void dataChanged(int type, int index) {
if(index > -1) {
index = getUnderlyingOffset(index);
if(index < 0) {
return;
}
}
for(int iter = 0 ; iter < listeners.size() ; iter++) {
((DataChangedListener)listeners.elementAt(iter)).dataChanged(type, index);
}
}
}

getting list of broken constraints for final best solution in drools-planner

I'm using drools-planner-5.4.0.CR1 and I wanna get list of broken constraints for final best solution
and also looked of examples of 5.4.0.CR1
I've implemented like in example but it returns empty list, in other words getScoreDetailList().size() is equal to 0, but solution.getScore() is equal to -54.
is there any suggestions?
public class SomeClass {
...
private volatile Solver solver;
private ScoreDirector scoreDirector;
...
public void someMethod() {
SolverFactory solverFactory = new XmlSolverFactory(SOLVER_CONFIG);
solver = solverFactory.buildSolver();
scoreDirector = solver.getScoreDirectorFactory().buildScoreDirector();
...
this.scoreDirector.setWorkingSolution(solution);
this.solver.setPlanningProblem(this.scoreDirector.getWorkingSolution());
this.solver.solve();
SomeSolution solution = (SomeSolution) solver.getBestSolution();
this.scoreDirector.setWorkingSolution(solution);
System.out.println( "Score: " + solution.getScore());
System.out.println( "getScoreDetailList size:" + getScoreDetailList().size());
}
public List<ScoreDetail> getScoreDetailList() {
if (!(scoreDirector instanceof DroolsScoreDirector)) {
return null;
}
Map<String, ScoreDetail> scoreDetailMap = new HashMap<String, ScoreDetail>();
WorkingMemory workingMemory = ((DroolsScoreDirector) scoreDirector).getWorkingMemory();
if (workingMemory == null) {
return Collections.emptyList();
}
Iterator<ConstraintOccurrence> it = (Iterator<ConstraintOccurrence>) workingMemory.iterateObjects(
new ClassObjectFilter(ConstraintOccurrence.class));
while (it.hasNext()) {
ConstraintOccurrence constraintOccurrence = it.next();
ScoreDetail scoreDetail = scoreDetailMap.get(constraintOccurrence.getRuleId());
if (scoreDetail == null) {
scoreDetail = new ScoreDetail(constraintOccurrence.getRuleId(), constraintOccurrence.getConstraintType());
scoreDetailMap.put(constraintOccurrence.getRuleId(), scoreDetail);
}
scoreDetail.addConstraintOccurrence(constraintOccurrence);
}
List<ScoreDetail> scoreDetailList = new ArrayList<ScoreDetail>(scoreDetailMap.values());
Collections.sort(scoreDetailList);
return scoreDetailList;
}
}
After
this.scoreDirector.setWorkingSolution(solution);
you forgot to call
this.scoreDirector.calculateScore();
I 'll docs about using Solver.getScoreDirectorFactory() in 5.4.0.Final.

Dynamically create node in lwuit for tree view

TreeModel model = new TreeModel() {
Node[] sillyTree = {
new Node("X", new Node[] {
new Node("Child 1", new Node[] {
}),
new Node("Child 2", new Node[] {
}),
new Node("Child 3", new Node[] {
}),
}),
new Node("Y", new Node[] {
new Node("A", new Node[] {
})
}),
new Node("Z", new Node[] {
new Node("A", new Node[] {
}),
}),
};
I want to create a node as dynacially,above sample code for static
plz help
See the TreeDemo class in UIDemo application. Here dynamically retrieve the values from file root and add that values into vector. See the FileTreeModel inner class from TreeDemo class. You can follow the same thing and add the dynamic values like that.
This might help -
class Node {
Vector children;
String value; // Name of the node….
public Node(String value, Vector children) {
this.children = children;
this.value = value;
}
public String toString() {
return value;
}
}
And -
Node[] nodeArray = generateRootNode();
TreeModel model = new TreeModel() {
Node[] sillyTree = nodeArray;
public Vector getChildren(Object parent) {
Node n = (Node) parent;
Object[] nodes = null;
Vector v = new Vector();
if (parent == null) {
nodes = sillyTree;
} else {
v = n.children;
}
if (nodes != null) {
for (int iter = 0; iter < nodes.length; iter++) {
v.addElement(nodes[iter]);
}
}
return v;
}
public boolean isLeaf(Object node) {
boolean returnValue = false;
try {
Node n = (Node) node;
returnValue = n.children == null || n.children.size() == 0;
} catch (ClassCastException ex) {
// It means its a child node or a leaf...
returnValue = true;
}
return returnValue;
}
};

Resources