This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
NoClassDefFoundError importing a library project
My blackberry application suddenly stopped working. My simulator or/and my application does not load up, I get the " Uncaught Exception: java.lang.NoClassDefFoundError ". I have not made any changes to my code since I last tested it. What has gone wrong?
package mypackage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Vector;
import javacard.framework.UserException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.location.Location;
import javax.microedition.location.LocationProvider;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.xmlpull.v1.XmlPullParserException;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.component.pane.TitleView;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.image.Image;
public class LoginTest extends UiApplication
{
public static void main(String[] args)
{
//Create a new instance of the app
//and start the app on the event thread.
LoginTest app = new LoginTest();
app.enterEventDispatcher();
}
public LoginTest()
{
//Display a new screen.
pushScreen(new LoginTestScreen());
}
}
//Create a new screen that extends MainScreen and provides
//behaviour similar to that of other apps.
final class LoginTestScreen extends MainScreen
{
//declare variables for later use
private InfoScreen _infoScreen;
private ObjectChoiceField choiceField;
private int select;
BasicEditField username;
PasswordEditField passwd;
CheckboxField checkBox1;
ButtonField loginBtn;
public LoginTestScreen()
{
//Invoke the MainScreen constructor.
super();
//Add a screen title.
setTitle("Track24ELMS");
LabelField login = new LabelField("ELMS Login", LabelField.FIELD_HCENTER);
login.setFont(Font.getDefault().derive(Font.BOLD, 30));
login.setMargin(10, 0, 20, 0); //To leave some space from top and bottom
HorizontalFieldManager user = new HorizontalFieldManager();
user.setMargin(0, 0, 10, 0);
HorizontalFieldManager pass = new HorizontalFieldManager();
pass.setMargin(0, 0, 20, 0);
HorizontalFieldManager checkbox = new HorizontalFieldManager();
checkbox.setMargin(0, 0, 30, 0);
HorizontalFieldManager btns = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
LabelField usernameTxt = new LabelField("Username :");
LabelField passwordTxt = new LabelField("Password :");
username = new BasicEditField();
passwd = new PasswordEditField();
loginBtn = new ButtonField("Login", ButtonField.CONSUME_CLICK);
loginBtn.setChangeListener(new LoginButtonListener());
checkBox1 = new CheckboxField("Remember me",false);
user.add(usernameTxt);
user.add(username);
pass.add(passwordTxt);
pass.add(passwd);
btns.add(loginBtn);
add(login);
add(user);
add(pass);
add(checkBox1);
add(btns);
}
private class LoginButtonListener implements FieldChangeListener {
public void fieldChanged(Field field, int context) {
//Open a new screen
String uname = username.getText();
String pwd = passwd.getText();
String sep = "</>";
//If there is no input
if (uname.length() == 0 || pwd.length()==0)
Dialog.alert("One of the textfield is empty!");
else
{
String URL = "http://xxx.xxx.com/xxx/xxx.asmx";
String METHOD_NAME = "ValidateCredentials";
String NAMESPACE = "http://tempuri.org/";
String SOAP_ACTION = NAMESPACE+METHOD_NAME;
//final String URL = "http://prerel.track24elms.com/Android/T24AndroidLogin.asmx/ValidateCredentials";
SoapObject resultRequestSOAP = null;
HttpConnection httpConn = null;
HttpTransport httpt;
System.out.println("The username" + uname + "password" + pwd );
SoapPrimitive response = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//String usernamecode = Base64.encode(uname.getBytes());
//String pwdEncodeString = Base64.encode(pwd.getBytes());
request.addProperty("username", uname);
request.addProperty("password", pwd);
System.out.println("The request is=======" + request.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.bodyOut = request;
envelope.dotNet = true;
//envelope.encodingStyle = SoapSerializationEnvelope.XSD;
envelope.setOutputSoapObject(request);
System.out.println("The envelope has the value++++"+ envelope.toString());
/* URL+ Here you can add paramter so that you can run on device,simulator etc. this will work only for wifi */
httpt = new HttpTransport(URL+ ";deviceside=true;ConnectionUID=S TCP");
//httpt.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
httpt.debug = true;
try
{
System.out.println("SOAP_ACTION == " + SOAP_ACTION);
httpt.call(SOAP_ACTION, envelope);
response = (SoapPrimitive) envelope.getResponse();
String result = response.toString();
System.out.println("response == " + result);
resultRequestSOAP = (SoapObject) envelope.bodyIn;
System.out.println("result == " + resultRequestSOAP);
String[] listResult = split(result, sep);
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("The exception is IO==" + e.getMessage());
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("The exception xml parser example==="
+ e.getMessage());
}
System.out.println( resultRequestSOAP);
//UiApplication.getUiApplication().pushScreen(new InfoScreen()); //Open a new Screen
}
}
};
private String[] split(String original, String separator) {
Vector nodes = new Vector();
int index = original.indexOf(separator);
while (index >= 0) {
nodes.addElement(original.substring(0, index));
original = original.substring(index + separator.length());
index = original.indexOf(separator);
}
nodes.addElement(original);
String[] result = new String[nodes.size()];
if (nodes.size() > 0) {
for (int loop = 0; loop < nodes.size(); loop++) {
result[loop] = (String) nodes.elementAt(loop);
System.out.println(result[loop]);
}
}
return result;
}
//To display a dialog box when a BlackBerry device user
//closes the app, override the onClose() method.
public boolean onClose()
{
Dialog.alert("Goodbye!");
System.exit(0);
return true;
}
//Create a menu item for BlackBerry device users to click to see more
//information about the city they select.
private MenuItem _viewItem = new MenuItem("More Info", 110, 10)
{
public void run()
{
//Store the index of the city the BlackBerry device user selects
select = choiceField.getSelectedIndex();
//Display a new screen with information about the
//city the BlackBerry device user selects
_infoScreen = new InfoScreen();
UiApplication.getUiApplication().pushScreen(_infoScreen);
}
};
//Create a menu item for BlackBerry device users to click to close
//the app.
private MenuItem _closeItem = new MenuItem("Close", 200000, 10)
{
public void run()
{
onClose();
}
};
//Create an inner class for a new screen that displays
//information about the city a BlackBerry device user selects.
private class InfoScreen extends MainScreen
{
String latitude, logitude, altitude;
public InfoScreen()
{
super();
setTitle("Itinerary");
LabelField login = new LabelField("Employee Itinerary", LabelField.FIELD_HCENTER);
HorizontalFieldManager userDetails = new HorizontalFieldManager();
userDetails.setMargin(0, 0, 10, 0);
HorizontalFieldManager statusBox = new HorizontalFieldManager();
statusBox.setMargin(0, 0, 20, 0);
HorizontalFieldManager locationDetails = new HorizontalFieldManager();
locationDetails.setMargin(0, 0, 30, 0);
HorizontalFieldManager imgBtn = new HorizontalFieldManager();
imgBtn.setMargin(0, 0, 40, 0);
//BitmapField userImg = new BitmapField(Bitmap.getBitmapResource("img1.jpg"));
LabelField userFetched = new LabelField("Sarah Farukh");
LabelField lastStatus = new LabelField("I am OK");
EditField statusMsg = new EditField("Status Message", "Update status here");
EditField lat = new EditField("Latitude", "latitude");
EditField longi = new EditField("Longitude", "logitude");
EditField alti = new EditField("Attitude", "altitude");
//BitmapField btnOK = new BitmapField(Bitmap.getBitmapResource("ok.png"),Field.FIELD_BOTTOM);
//BitmapField btnNO = new BitmapField(Bitmap.getBitmapResource("no.png"),Field.FIELD_BOTTOM);
//BitmapField btnHN = new BitmapField(Bitmap.getBitmapResource("hn.png"),Field.FIELD_BOTTOM);
//userDetails.add(userImg);
userDetails.add(userFetched);
userDetails.add(lastStatus);
statusBox.add(userFetched);
locationDetails.add(lat);
locationDetails.add(longi);
locationDetails.add(alti);
//imgBtn.add(btnOK);
//imgBtn.add(btnNO);
//imgBtn.add(btnHN);
add(login);
add(userDetails);
add(statusBox);
add(locationDetails);
add(imgBtn);
}
}
}
It is possible that you are accessing a class in a separate library. You have set up your project so that the class is found at build time.
If that library was not deployed to the device for some reason (forgot to? error when deploying?), then your class will not be found at runtime.
Either make sure to deploy this library properly onto the device (by uploading the correct compiled COD file).
Or include the library into your project by setting up your build path correctly.
(my answer based on this one: NoClassDefFoundError importing a library project)
Related
I made a very simple test gui based on this brilliant article about getting started with Esper.
What surprises me is that this query is validated to true after the very first tick event is sent, if the price is above 6.
select * from StockTick(symbol='AAPL').win:length(2) having avg(price) > 6.0
As far as I understand, win:length(2) needs TWO ticks before an event is fired, or am I wrong?
Here is a SSCCE for this question, just press the "Create Tick Event" button and you will see the StockTick Event being fired at once.
It needs the following jars which comes bundled with Esper
esper\lib\antlr-runtime-3.2.jar
esper\lib\cglib-nodep-2.2.jar
esper\lib\commons-logging-1.1.1.jar
esper\lib\esper_3rdparties.license
esper\lib\log4j-1.2.16.jar
esper-4.11.0.jar
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.Random;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import com.espertech.esper.client.Configuration;
import com.espertech.esper.client.EPAdministrator;
import com.espertech.esper.client.EPRuntime;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPServiceProviderManager;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.UpdateListener;
import javax.swing.JTextField;
public class Tester extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton createRandomValueEventButton;
private JPanel panel;
private JPanel southPanel;
private JPanel centerPanel;
private static JTextArea centerTextArea;
private static JTextArea southTextArea;
private static Random generator = new Random();
private EPRuntime cepRT;
private JSplitPane textSplitPane;
private JButton btnNewButton;
private static JTextField priceTextField;
public Tester() {
getContentPane().setLayout(new BorderLayout(0, 0));
JSplitPane splitPane = new JSplitPane();
createRandomValueEventButton = new JButton("Create Tick Event With Random Price");
splitPane.setLeftComponent(createRandomValueEventButton);
createRandomValueEventButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
createTickWithRandomPrice();
}
});
panel = new JPanel();
splitPane.setRightComponent(panel);
panel.setLayout(new GridLayout(1, 0, 0, 0));
btnNewButton = new JButton("Create Tick Event");
panel.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
createTick();
}
});
priceTextField = new JTextField();
priceTextField.setText(new Integer(10).toString());
panel.add(priceTextField);
priceTextField.setColumns(4);
getContentPane().add(splitPane, BorderLayout.NORTH);
textSplitPane = new JSplitPane();
textSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
getContentPane().add(textSplitPane, BorderLayout.CENTER);
centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout(0, 0));
JScrollPane centerTextScrollPane = new JScrollPane();
centerTextScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
centerTextArea = new JTextArea();
centerTextArea.setRows(12);
centerTextScrollPane.setViewportView(centerTextArea);
southPanel = new JPanel();
southPanel.setLayout(new BorderLayout(0, 0));
JScrollPane southTextScrollPane = new JScrollPane();
southTextScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
southTextArea = new JTextArea();
southTextArea.setRows(5);
southTextScrollPane.setViewportView(southTextArea);
textSplitPane.setRightComponent(southTextScrollPane);
textSplitPane.setLeftComponent(centerTextScrollPane);
setupCEP();
}
public static void GenerateRandomTick(EPRuntime cepRT) {
double price = (double) generator.nextInt(10);
long timeStamp = System.currentTimeMillis();
String symbol = "AAPL";
Tick tick = new Tick(symbol, price, timeStamp);
System.out.println("Sending tick:" + tick);
centerTextArea.append(new Date().toString()+" Sending tick:" + tick+"\n");
cepRT.sendEvent(tick);
}
public static void GenerateTick(EPRuntime cepRT) {
double price = Double.parseDouble(priceTextField.getText());
long timeStamp = System.currentTimeMillis();
String symbol = "AAPL";
Tick tick = new Tick(symbol, price, timeStamp);
System.out.println("Sending tick:" + tick);
centerTextArea.append(new Date().toString()+" Sending tick: " + tick+"\n");
cepRT.sendEvent(tick);
}
public static void main(String[] args){
Tester tester = new Tester();
tester.setSize(new Dimension(570,500));
tester.setVisible(true);
}
private void createTickWithRandomPrice(){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GenerateRandomTick(getEPRuntime());
}
});
}
private void createTick(){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GenerateTick(getEPRuntime());
}
});
}
private void setupCEP(){
Configuration cepConfig = new Configuration();
cepConfig.addEventType("StockTick", Tick.class.getName());
EPServiceProvider cep = EPServiceProviderManager.getProvider("myCEPEngine", cepConfig);
cepRT = cep.getEPRuntime();
EPAdministrator cepAdm = cep.getEPAdministrator();
EPStatement cepStatement = cepAdm.createEPL(
"select * from " +
"StockTick(symbol='AAPL').win:length(2) " +
"having avg(price) > 6.0");
cepStatement.addListener(new CEPListener());
//System.out.println("cepStatement.getText(): "+cepStatement.getText());
}
private EPRuntime getEPRuntime(){
public static class Tick {
String symbol;
Double price;
Date timeStamp;
public Tick(String s, double p, long t) {
symbol = s;
price = p;
timeStamp = new Date(t);
}
public double getPrice() {return price;}
public String getSymbol() {return symbol;}
public Date getTimeStamp() {return timeStamp;}
#Override
public String toString() {
return symbol+" Price: " + price.toString();
}
}
public static class CEPListener implements UpdateListener {
}
Actually aggregation and conditions are independent of how many events are in data window. There are functions you could use to check whether a data window is "filled": the "leaving", "count" or "prevcount" for example.
For anyone interested,
changing the query to this solved the problem
select * from StockTick(symbol='AAPL').win:length_batch(2) having avg(price) > 6.0 and count(*) >= 2
Now an event will be triggered for every consecutive tick with the price higher than 6, in batches of two.
I'm trying to use Primefaces's dataExporter component. I have two problems with it (for now):
In column footers of datatable I have a p:commandButton. What happens to me is that when I export datatable with dataExporter to PDF I can see that it added column footers to PDF and wrote something like this: javax.faces.component.UIPanel#9e08b9 (it just called toString of UIComponent I suppose). Is there any way to instruct dataExporter to ignore column footers?
I want to try to somehow open new window with generated PDF and show that PDF inline on a new page. I don't wont to see Download file prompt. Is this possible?
After some time, and coding I finally succeeded to make this work. Primefaces doesn't have this functions included so I have to override default behavior little bit.
First I created custom PDFExporter to skip footer printing:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.component.export.PDFExporter;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPTable;
public class CustomPDFExporter extends PDFExporter {
#Override
protected void addColumnFacets(DataTable table, PdfPTable pdfTable,
ColumnType columnType) {
if (columnType == ColumnType.HEADER) {
super.addColumnFacets(table, pdfTable, columnType);
}
}
#Override
protected void writePDFToResponse(ExternalContext externalContext,
ByteArrayOutputStream baos, String fileName) throws IOException,
DocumentException {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.put("reportBytes", baos.toByteArray());
FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.put("reportName", fileName);
}
}
As you can see, report data is added in session.
Now DataExporter of Primefaces should be rewriten:
import java.io.IOException;
import javax.el.ELContext;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.FacesException;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.component.export.CSVExporter;
import org.primefaces.component.export.Exporter;
import org.primefaces.component.export.ExporterType;
import org.primefaces.component.export.XMLExporter;
import org.primefaces.context.RequestContext;
import asw.iis.common.ui.beans.DatatableBackingBean;
public class CustomDataExporter implements ActionListener, StateHolder {
private ValueExpression target;
private ValueExpression type;
private ValueExpression fileName;
private ValueExpression encoding;
private MethodExpression preProcessor;
private MethodExpression postProcessor;
private DatatableBackingBean<?> datatableBB;
public CustomDataExporter() {}
public CustomDataExporter(ValueExpression target, ValueExpression type, ValueExpression fileName, ValueExpression encoding,
MethodExpression preProcessor, MethodExpression postProcessor, DatatableBackingBean<?> datatableBB) {
this.target = target;
this.type = type;
this.fileName = fileName;
this.encoding = encoding;
this.preProcessor = preProcessor;
this.postProcessor = postProcessor;
this.datatableBB = datatableBB;
}
public void processAction(ActionEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
try {
datatableBB.stampaPreProcess();
ELContext elContext = context.getELContext();
String tableId = (String) target.getValue(elContext);
String exportAs = (String) type.getValue(elContext);
String outputFileName = (String) fileName.getValue(elContext);
String encodingType = "UTF-8";
if(encoding != null) {
encodingType = (String) encoding.getValue(elContext);
}
try {
Exporter exporter;
ExporterType exporterType = ExporterType.valueOf(exportAs.toUpperCase());
switch(exporterType) {
case XLS:
exporter = new ExcelExporter();
break;
case PDF:
exporter = new CustomPDFExporter();
break;
case CSV:
exporter = new CSVExporter();
break;
case XML:
exporter = new XMLExporter();
break;
default:
exporter = new CustomPDFExporter();
break;
}
UIComponent component = event.getComponent().findComponent(tableId);
if(component == null) {
throw new FacesException("Cannot find component \"" + tableId + "\" in view.");
}
if(!(component instanceof DataTable)) {
throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName() + "\", exporter must target a PrimeFaces DataTable.");
}
DataTable table = (DataTable) component;
exporter.export(context, table, outputFileName, false, false, encodingType, preProcessor, postProcessor);
if ("pdf".equals(exportAs)) {
String path = ((ServletContext)(FacesContext.getCurrentInstance().getExternalContext().getContext())).getContextPath();
RequestContext.getCurrentInstance().execute("window.open('" + path + "/report.pdf', '_blank', 'dependent=yes, menubar=no, toolbar=no')");
} else {
context.responseComplete();
}
}
catch (IOException e) {
throw new FacesException(e);
}
}
finally {
((HttpServletRequest) context.getExternalContext().getRequest()).removeAttribute("vrstaStampe");
datatableBB.stampaPostProcess();
}
}
public boolean isTransient() {
return false;
}
public void setTransient(boolean value) {
}
public void restoreState(FacesContext context, Object state) {
Object values[] = (Object[]) state;
target = (ValueExpression) values[0];
type = (ValueExpression) values[1];
fileName = (ValueExpression) values[2];
preProcessor = (MethodExpression) values[3];
postProcessor = (MethodExpression) values[4];
encoding = (ValueExpression) values[5];
datatableBB = (DatatableBackingBean<?>) values[6];
}
public Object saveState(FacesContext context) {
Object values[] = new Object[7];
values[0] = target;
values[1] = type;
values[2] = fileName;
values[3] = preProcessor;
values[4] = postProcessor;
values[5] = encoding;
values[6] = datatableBB;
return ((Object[]) values);
}
}
Main job here is to instantiate CustomPDFExporter, and open new window in case when report type is PDF.
Now I wrote simple Servlet to handle this request and print report data:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/report.pdf")
public class PdfReportServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
byte[] b = (byte[]) req.getSession().getAttribute("reportBytes");
if (b == null) {
b = new byte[0];
}
resp.setContentType("application/pdf");
resp.setContentLength(b.length);
resp.getOutputStream().write(b);
req.getSession().removeAttribute("reportBytes");
}
}
This will configure HTTP header, and print bytes of report to output stream. Also it removes report bytes from session.
Finally, as I handle this printing from dynamically created menu button I add this action listener in code:
MenuItem item = ...;
ELContext el = FacesContext.getCurrentInstance().getELContext();
ExpressionFactory ef = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
ValueExpression typeEL = ef.createValueExpression(el, "#{startBean.reportType}", String.class);
ValueExpression fileEL = ef.createValueExpression(el, datasource, String.class);
ValueExpression targetEL = ef.createValueExpression(el, ":" + datatableId + ":datatableForm:datatable", String.class);
ValueExpression encodingEL = ef.createValueExpression(el, "ISO-8859-2", String.class);
CustomDataExporter de = new CustomDataExporter(targetEL, typeEL, fileEL, encodingEL, null, null, this);
item.setAjax(true);
item.addActionListener(de);
code is working properly.but i am not able to display the final data which is from "setDataURL("ds/test_data/employees.data.xml".so tel me where shud i create dis file and how to create.
package com.smartgwt.sample.showcase.client;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.fields.DataSourceFloatField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.google.gwt.i18n.client.NumberFormat;
import com.smartgwt.sample.showcase.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Showcase implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
RootPanel.get().add(getViewPanel());
}
public Canvas getViewPanel() {
EmployeeXmlDS employeesDS = EmployeeXmlDS.getInstance();
TreeGrid treeGrid = new TreeGrid();
treeGrid.setCanEdit(true);
treeGrid.setLoadDataOnDemand(false);
treeGrid.setWidth(500);
treeGrid.setHeight(400);
treeGrid.setDataSource(employeesDS);
treeGrid.setNodeIcon("icons/16/person.png");
treeGrid.setFolderIcon("icons/16/person.png");
treeGrid.setShowOpenIcons(false);
treeGrid.setShowDropIcons(false);
treeGrid.setClosedIconSuffix("");
treeGrid.setAutoFetchData(true);
TreeGridField nameField = new TreeGridField("Name");
TreeGridField jobField = new TreeGridField("Job");
TreeGridField salaryField = new TreeGridField("Salary");
salaryField.setCellFormatter(new CellFormatter() {
public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
if (value != null) {
NumberFormat nf = NumberFormat.getFormat("#,##0");
try {
return "$" + nf.format(((Number) value).longValue());
} catch (Exception e) {
return value.toString();
}
} else {
return null;
}
}
});
treeGrid.setFields(nameField, jobField, salaryField);
return treeGrid;
}
}
class EmployeeXmlDS extends DataSource {
private static EmployeeXmlDS instance = null;
public static EmployeeXmlDS getInstance() {
if (instance == null) {
instance = new EmployeeXmlDS("employeesDS");
}
return instance;
}
public EmployeeXmlDS(String id) {
setID(id);
setTitleField("Name");
setRecordXPath("/List/employee");
DataSourceTextField nameField = new DataSourceTextField("Name", "Name", 128);
DataSourceIntegerField employeeIdField = new DataSourceIntegerField("EmployeeId", "Employee ID");
employeeIdField.setPrimaryKey(true);
employeeIdField.setRequired(true);
DataSourceIntegerField reportsToField = new DataSourceIntegerField("ReportsTo", "Manager");
reportsToField.setRequired(true);
reportsToField.setForeignKey(id + ".EmployeeId");
reportsToField.setRootValue("1");
DataSourceTextField jobField = new DataSourceTextField("Job", "Title", 128);
DataSourceTextField emailField = new DataSourceTextField("Email", "Email", 128);
DataSourceTextField statusField = new DataSourceTextField("EmployeeStatus", "Status", 40);
DataSourceFloatField salaryField = new DataSourceFloatField("Salary", "Salary");
DataSourceTextField orgField = new DataSourceTextField("OrgUnit", "Org Unit", 128);
DataSourceTextField genderField = new DataSourceTextField("Gender", "Gender", 7);
genderField.setValueMap("male", "female");
DataSourceTextField maritalStatusField = new DataSourceTextField("MaritalStatus",
"Marital Status", 10);
setFields(nameField, employeeIdField, reportsToField, jobField, emailField, statusField,
salaryField, orgField, genderField, maritalStatusField);
setDataURL("ds/test_data/employees.data.xml");
setClientOnly(true);
}
}
Please anyone help me get selected listitems from a listfieldcheckbox, and add them into an arraylist. If possible, give any useful links also. Here's my code so far (I am new to blackberry application development). Please help.
package mypackage;
import java.util.Vector;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.IntVector;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen implements ListFieldCallback
{
private Vector _listData = new Vector();
private Vector _checkedData = new Vector();
private ListField listField;
private static final String[] _elements = {"First element", "Second element","Third element"
};
//private static final String[] _elements1 = {"hai","welcome","where r u"
//};
private MenuItem _getDataMenu,selectall,Delete;
Vector result = new Vector();
protected void makeMenu(Menu menu, int instance)
{
menu.add(_getDataMenu);
menu.add(selectall);
menu.add(Delete);
//Create the default menu.
super.makeMenu(menu, instance);
}
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
public Vector getCheckedItems() {
return _checkedData;
}
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
VerticalFieldManager main = new VerticalFieldManager(VerticalFieldManager.USE_ALL_HEIGHT|
VerticalFieldManager.USE_ALL_WIDTH|VerticalFieldManager.VERTICAL_SCROLL);
this.add(main);
HorizontalFieldManager hfm = new HorizontalFieldManager();
main.add(hfm);
listField = new ListField(){
//Allow the space bar to toggle the status of the selected row.
protected boolean keyChar(char key, int status, int time)
{
boolean retVal = false;
//If the spacebar was pressed...
if (key == Characters.SPACE)
{
//Get the index of the selected row.
int index = getSelectedIndex();
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index);
//Invalidate the modified row of the ListField.
invalidate(index);
//Consume this keyChar (key pressed).
retVal = true;
}
return retVal;
}
};
listField.setCallback(this);
reloadList();
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.addElement(new ChecklistData(_elements[count], false));
//_listData.addElement(new ChecklistData(_elements1[count], false));
listField.insert(count);
}
main.add(listField);
_getDataMenu =new MenuItem("Get Data", 200, 10) {
public void run(){
int index = listField.getSelectedIndex();
ChecklistData data = (ChecklistData)_listData.elementAt(index);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
//Dialog.alert(message);
// get all the checked data indices
IntVector selectedIndex = new IntVector(0, 1);
//ChecklistData data;
for (int i=0;i<_listData.size();i++) {
data = (ChecklistData)_listData.elementAt(i);
if(data.isChecked()) {
selectedIndex.addElement(i);
String selectedvalues = data.getStringVal();
System.out.println("Selected items are:"+selectedvalues);
}
}
data = null;
// now selectedIndex will contain all the checked data indices.
//String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
}
};
selectall = new MenuItem("Selectall", 200, 10){
public void run(){
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.setElementAt(new ChecklistData(_elements[count], true), count);
}
}
};
Delete = new MenuItem("Delete", 200, 10){
public void run(){
int index = listField.getSelectedIndex();
_listData.removeElementAt(index);
// update the view
listField.delete(index);
listField.invalidate(index);
}
};
}
private void reloadList() {
// TODO Auto-generated method stub
_listData.setSize(_listData.size());
}
public void drawListRow(ListField list, Graphics graphics, int index, int y, int w)
{
ChecklistData currentRow = (ChecklistData)this.get(list, index);
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked())
{
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else
{
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);
/*if (currentRow.isChecked()) {
if( -1 ==_checkedData.indexOf(currentRow))
_checkedData.addElement(currentRow);
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else {
if( -1 !=_checkedData.indexOf(currentRow))
_checkedData.removeElement(currentRow);
rowString.append(Characters.BALLOT_BOX);
} */
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
}
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
return _listData.indexOf(p, s);
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
protected boolean navigationClick(int status, int time) {
int index1 = listField.getSelectedIndex();
/*System.out.println("Selected item index:"+index1);
//int[] list =listField.getSelection();
//String s = Integer.toString(list);
System.out.println(" items are:"+_elements[index1]);
//ChecklistData data = (ChecklistData)_listData.elementAt(index1);*/
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index1);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
System.out.println("message is:"+message);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index1);
//Invalidate the modified row of the ListField.
listField.invalidate(index1);
return true;
}
}
I am use a button and when u click this button a text field is automatic created and button status is automatic disable but if u click on disable button text field is automatic delete and button status is changed to enable.i going through this process.
public class ConfigurationScreen extends MainScreen implements FieldChangeListener{
TextField tf_text;
tf_text = new TextField(TextField.TYPE_PLAIN,img_text[1],img_text[0],TextField.FIELD_HCENTER);
tf_text.setWidth(Display.getWidth()/2+20);
ImageButton btn_en;
btn_en = new ImageButton(imgs_tmintrvl1,"enable",ImageButton.FIELD_HCENTER);
ImageButton btn_dis;
btn_dis=new ImageButton(imgs_tmintrvl1,"Disable",ImageButton.FIELD_HCENTER);
add(btn_en);
btn_en.setChangeListener(this);
public void fieldChanged(Field field, int context) {
if( field==btn_en)
{
delete(btn_en);
insert(btn_dis, 4);
insert(tf_text, 5);
System.out.println(ex);
}else if (field == btn_dis){
delete(btn_dis);
delete(tf_text);
insert(btn_en, 4);
System.out.println("Disable Button="+ex);
}
}
But when i run this code i am getting null pointerr exception please help me where i am making mistake.
package org.maxmobility.wmp.beta;
import com.maxmobility.customfield.H_FieldManager;
import com.maxmobility.customfield.ImageButton;
import com.maxmobility.customfield.LabelField;
import com.maxmobility.customfield.PillButtonField;
import com.maxmobility.customfield.PillButtonSet;
import com.maxmobility.customfield.TextArea;
import com.maxmobility.customfield.TextField;
import com.maxmobility.util.AppColors;
import net.rim.device.api.collection.List;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.FocusChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;
public class ConfigurationScreen extends MainScreen implements FieldChangeListener{
TextField tf_phn1;
TextField tf_phn2;
TextField tf_msg;
TextArea ta_msg;
ImageButton btn_add;
ImageButton btn_subtract;
ImageButton btn_en;
ImageButton btn_dis;
ImageButton btn_time1, btn_time2, btn_time3;
LabelField lf_msg;
LabelField lf_time;
LabelField lf1,lf2,lf3,lf4;
private Bitmap[] imgs_addbtn;
private Bitmap[] imgs_subbtn;
private Bitmap[] imgs_tmintrvl1;
private Bitmap[] imgs_tmintrvl2;
private Bitmap[] imgs_tmintrvl3;
private EncodedImage[] img_text;
private H_FieldManager hfm1 , hfm2;
private HorizontalFieldManager hfm3,hfm4;
private VerticalFieldManager vfm;
private boolean show = false;
PillButtonField pbf1;
PillButtonField pbf2;
PillButtonField pbf3;
PillButtonSet pbf_set;
public ConfigurationScreen(){
super(USE_ALL_HEIGHT | USE_ALL_WIDTH);
Background background = BackgroundFactory
.createSolidBackground(AppColors.APP_BG);
this.getMainManager().setBackground(background);
LabelField lf = new LabelField("Configuration Screen", LabelField.FIELD_HCENTER | LabelField.USE_ALL_WIDTH);
lf.setColor(Color.RED);
setTitle(lf);
img_text = new EncodedImage[2];
img_text[0] = EncodedImage.getEncodedImageResource("edittext_selected.png");
img_text[1] = EncodedImage.getEncodedImageResource("edittext.png");
imgs_addbtn = new Bitmap[3];
imgs_addbtn[0] = Bitmap.getBitmapResource("btn_add_sub.png");
imgs_addbtn[1] = Bitmap.getBitmapResource("btn_add_subfocused.png");
imgs_addbtn[2] = Bitmap.getBitmapResource("btn_add_subfocused.png");
imgs_subbtn = new Bitmap[3];
imgs_subbtn[0] = Bitmap.getBitmapResource("btn_add_sub.png");
imgs_subbtn[1] = Bitmap.getBitmapResource("btn_add_subfocused.png");
imgs_subbtn[2] = Bitmap.getBitmapResource("btn_add_subfocused.png");
imgs_tmintrvl1 = new Bitmap[3];
imgs_tmintrvl1[0] = Bitmap.getBitmapResource("default_btn_Unfocused.png");
imgs_tmintrvl1[1] = Bitmap.getBitmapResource("default_btn_focused.png");
imgs_tmintrvl1[2] = Bitmap.getBitmapResource("default_btn_focused.png");
// imgs_tmintrvl2 = new Bitmap[3];
// imgs_tmintrvl2[0] = Bitmap.getBitmapResource("default_btn_Unfocused.png");
// imgs_tmintrvl2[1] = Bitmap.getBitmapResource("default_btn_focused.png");
// imgs_tmintrvl2[2] = Bitmap.getBitmapResource("default_btn_focused.png");
//
// imgs_tmintrvl3 = new Bitmap[3];
// imgs_tmintrvl3[0] = Bitmap.getBitmapResource("default_btn_Unfocused.png");
// imgs_tmintrvl3[1] = Bitmap.getBitmapResource("default_btn_focused.png");
// imgs_tmintrvl3[2] = Bitmap.getBitmapResource("default_btn_focused.png");
//
tf_phn1 = new TextField(TextField.TYPE_PHONE,img_text[1],img_text[0],TextField.FIELD_LEFT);
tf_phn2 = new TextField(TextField.TYPE_PHONE,img_text[1],img_text[0],TextField.FIELD_LEFT);
tf_msg = new TextField(TextField.TYPE_PLAIN,img_text[1],img_text[0],TextField.FIELD_HCENTER);
tf_phn1.setWidth(Display.getWidth()/2+50);
tf_phn2.setWidth(Display.getWidth()/2+50);
tf_msg.setWidth(Display.getWidth()/2+95);
ta_msg = new TextArea(Display.getWidth()/2+130, 100,TextArea.FIELD_HCENTER);
btn_add = new ImageButton(imgs_addbtn," +",ImageButton.FIELD_HCENTER);
btn_subtract = new ImageButton(imgs_subbtn," -",ImageButton.FIELD_RIGHT);
btn_en = new ImageButton(imgs_tmintrvl1,"Enable",ImageButton.FIELD_HCENTER);
btn_dis = new ImageButton(imgs_tmintrvl1,"Disable",ImageButton.FIELD_HCENTER);
// btn_time1 = new ImageButton(imgs_tmintrvl1, "15 min",ImageButton.FIELD_LEFT);
// btn_time2 = new ImageButton(imgs_tmintrvl1, "30 min",ImageButton.FIELD_HCENTER);
// btn_time3 = new ImageButton(imgs_tmintrvl1, "45 min",ImageButton.FIELD_RIGHT);
// btn_time1.set_Margin(35,0, 0,0);
// btn_time2.set_Margin(0,0, 0,0);
// btn_time3.set_Margin(0,0, 0,0);
//btn_add.set_Margin(0,0, 8,8);
LabelField lf1 = new LabelField("",Display.getWidth(),45,LabelField.FIELD_LEFT);
LabelField lf2 = new LabelField("",Display.getWidth(),45,LabelField.FIELD_LEFT);
LabelField lf3 = new LabelField("",Display.getWidth(),45,LabelField.FIELD_LEFT);
LabelField lf4 = new LabelField("",Display.getWidth(),45,LabelField.FIELD_LEFT);
lf_msg = new LabelField("Alert Message",LabelField.FIELD_LEFT);
lf_msg.set_pos(35,0);
lf_time = new LabelField("Select Time Interval",LabelField.FIELD_LEFT);
lf_time.set_pos(35,20);
pbf1 = new PillButtonField("15 min");
pbf2 = new PillButtonField("30 min");
pbf3 = new PillButtonField("45 min");
pbf_set = new PillButtonSet(300,40);
pbf_set.add(pbf1);
pbf_set.add(pbf2);
pbf_set.add(pbf3);
hfm1 = new H_FieldManager(tf_phn1, btn_add, true, H_FieldManager.FIELD_HCENTER);
hfm2 = new H_FieldManager(tf_phn2, btn_subtract, true, H_FieldManager.FIELD_HCENTER);
// hfm3 = new HorizontalFieldManager(HORIZONTAL_SCROLL_MASK);
hfm4 = new HorizontalFieldManager(pbf1.FIELD_HCENTER);
// hfm3.add(btn_time1);
// hfm3.add(btn_time2);
// hfm3.add(btn_time3);
hfm4.add(pbf_set);
vfm = new VerticalFieldManager();
add(lf1);
add(hfm1);
add(lf_msg);
//add(tf_msg);
add(ta_msg);
add(btn_en);
add(lf_time);
//add(hfm3);
add(hfm4);
System.out.println(" insert label");
btn_add.setChangeListener(this);
btn_subtract.setChangeListener(this);
btn_en.setChangeListener(this);
btn_dis.setChangeListener(this);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if(field == btn_add){
insert(hfm2, 2);
}else if(field == btn_subtract){
delete(hfm2);
//}
}else if(field == btn_en){
replace(btn_en, btn_dis);
insert(tf_msg, 5);
}else if(field == btn_dis){
replace(btn_dis, btn_en);
delete(tf_msg);
}
}
}
I hope your Problem will solve in this code.