rms queries, find a phrase inside a text - java-me

I want to do a midlet application for save product with its bar code, product's name, product's description and price. Then it is going to be saved as it:
123123123-coca cola-soda-6.50
124512341-crystal coca-soda-7.00
well for this I have built this code:
public boolean ProductoAgregar(String dato) // add product
{
byte bytes[] = dato.getBytes();
try {
rs.addRecord(bytes, 0, bytes.length);
return true;
} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
}
}
public boolean ProductoModificar(String dato, int id) // update product
{
try
{
byte bytes[] = dato.getBytes();
rs.setRecord(id, bytes, 0, dato.length());
return true;
}
catch(Exception ex)
{
return false;
}
}
public boolean ProductoEliminar(int id)// delete product
{
try
{
rs.deleteRecord(id);
return true;
}
catch(Exception ex)
{
return false;
}
}
I don't have an idea for how to create the method for find a product (with a part of its name, or with its bar code) and what is going to return? maybe an array?
For example all products has write coca in its name (or in description) or
find a unique product with bar code.
(This is a class with I'll instance for use its methods)

you can try following code, by editing as per your usage. I am using below code for searching an item from RMS Data.
public boolean SearchRecord(String Rec, int pos )
{
String [] data = getRecordData();
Rec = Rec.substring(0,pos);
for ( int i = 0 ; i < data.length ; i++ )
{
data[i] = data[i].substring(0, pos );
if ( Rec.toString().trim().equals(data[i].toString().trim()) )
{
data = null; // System.gc();
return true;
}
}
data = null; // System.gc();
return false;
}
By Changing the value of "pos" variable you can achieve your goal.

Related

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

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.

J2ME Login and Search Record Store

I'm new to J2ME and I'm taking a class where we use it. I created a simple travel reservation MIDlet using choice groups text fields etc. I then added a Record Store to capture this information. I now have a user login that only requires a user name, but i don't know how to verify that the user name is in the Record Store, so instead I accept any one as long as the Textfield for the user name is not empty. My first question is how would I verify that the user exist, I already can create an account. The second question is how can I search a record store not by id but say using a string within a certain range for each row of the Record store.
Here is my code so far:
$import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.util.Date;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;
/**
* #author XayBlu
*/
public class tripMe extends MIDlet implements CommandListener {
Form startForm, airForm, trainForm, cruiseForm, autoForm, Ext, Pass,home,login, create;
Command Exit, Trip, Cinfo, AutC,AiC,CrC, info,Tme,trainC, logC,signC, createC, prev, newTrip, Home;
ChoiceGroup trans,hCAP, passCNT,airT,airC,AuC,AuT,CrL,CcabT,Tseat,TOP;
Display Xdisplay;
TextField Eneed, uName, uName2;
Alert Final, FinalT, Sucess, nope;
DateField dDate, rDate;
Date d,r;
Image [] image;
String details =" ",tt="", Trav, Rdate, Ddate, extraA, Pcount,specialA, TT,AIR2, AIR,AUTO,AUTO2,CRUISE,CRUISE2,TRAIN,TRAIN2, USERS="USERS";
String op[] = {"Air","Auto","Cruise","Train"}; //Array Items for Choice Groups
String ep[] = {"Wheel Chair","Baby Seat","Extended Seatbelt","Extra Pillows","Oxygen Tank","GPS"};
String count[] = {"1","2","3","4","5","6","7","8"};
String AL []= {"American Airlines","Delta","US Airways","South West Airlines","United Airlines"};
String Rental [] = {"Alamo","Avis","Budget","Enteprise","Dollar","Hertz"};
String CL [] = {"Carnival","Norwegian","Royal Caribbean","Celebrity X","MSC"};
String CT [] = {"Compact","Standard","Full","SUV","Luxury","Sports"};
String Cabin [] = {"Suite","Ocean Balcony","Standard","Economy"};
String tCAB[] = {"Standard Seat","Sleeper Cart"};
String Toptions[] ={"Extra Luggage room","Salad Buffet","Wifi Access","Extra Blanket"};
RecordStore usr,itt;
RecordEnumeration recEnum = null;
RecordFilter filter = null;
int Umax=5;
int tran1 =6;
String last;
Byte [] data = new Byte[Umax];
/* NEW COMMANDS FOR FLEXIBLE USER INPUT TO RECORD STORES */
public void writeRecord(String str){ // User to insert user input to record stores
byte[] rec = str.getBytes();
try{
usr.addRecord(rec, 0, rec.length);
}catch (Exception e){}
}
public void writeInfo(String str){ // User to insert user input to record stores
byte[] rec = str.getBytes();
try{
usr.addRecord(rec, tran1, rec.length);
}catch (Exception e){}
}
public void updateRecord(String str){
try{
usr.setRecord(1, str.getBytes(), 0, str.length());
}catch (Exception e){}
}
public void deleteRecord(){
try{
usr.deleteRecord(1);
}catch (Exception e){}
}
public void closeRecord(){
try{
usr.closeRecordStore();
}catch (Exception e){}
}
public void deleteRecStore(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(USERS);
}catch (Exception e){}
}
}
public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
usr = RecordStore.openRecordStore(USERS, true );
}
catch (Exception e)
{
System.out.print("Could not open record store");
}
}
public void readRecords()
{
try
{
// Intentionally make this too small to test code below
byte[] recData = new byte[5];
int len;
for (int i = 1; i <= usr.getNumRecords(); i++)
{
if (usr.getRecordSize(i) > recData.length)
recData = new byte[usr.getRecordSize(i)];
len = usr.getRecord(i, recData, 0);
home.append(new String(recData,0,len));
// System.out.println("Record #" + i + ": " + new String(recData, 0, len));
// System.out.println("------------------------------");
}
}
catch (Exception e)
{
nope = new Alert("Sorry no match!",null,null,AlertType.INFO);
nope.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(nope, login);
}
}
}
class Filter implements RecordFilter {
private String search = null;
private ByteArrayInputStream inputstream = null;
private DataInputStream datainputstream = null;
public Filter(String search) {
this.search = search.toLowerCase();
}
public void filterClose() {
try {
if (inputstream != null) {
inputstream.close();
}
if (datainputstream != null) {
datainputstream.close();
}
} catch (Exception error) {
}
}
}
public tripMe (){
try{ //Initializing individual images for Choice Group Icons
Image car = Image.createImage("/car2.png");
Image plane = Image.createImage("/plane2.png");
Image train = Image.createImage("/train2.png");
Image cruise = Image.createImage("/cruise2.png");
image = new Image[] {plane,car,cruise,train}; //Initializing Image array for ChoiceGroup
}
catch (java.io.IOException err) {System.out.print("Could not load pics"); } //Throws exception if pic cannot be found
startForm = new Form("Get Away Today"); //Initialization of forms
Pass = new Form ("Passenger Information");
airForm = new Form("Low Prices!");
autoForm = new Form("Find the best car for you");
Ext = new Form("Itinerary Details");
Ext.setTicker(new Ticker("Enjoy Your Vacation"));
cruiseForm = new Form("Sail Away Today");
trainForm = new Form("Chuuu- Chuuu");
login = new Form("Sign up Today");
home = new Form("Welcome Back");
create = new Form("Create an account");
trans = new ChoiceGroup("Select travel type",ChoiceGroup.EXCLUSIVE,op,image); //Transport tation choice group initialized with corresponding string and image array
Exit = new Command("Exit", Command.EXIT,1);//Adding necessary commands
Trip = new Command("Go", Command.SCREEN,2);//Adding go command which allows you to select travel type
signC = new Command("Sign up",Command.SCREEN,2);
logC = new Command("Log in",Command.SCREEN,2);
createC = new Command("OK",Command.SCREEN,2);
prev = new Command("History",Command.SCREEN,2);
newTrip = new Command("Reservations",Command.SCREEN,2);
Home = new Command("Log out",Command.SCREEN,1);
hCAP = new ChoiceGroup("Extra Assistance", ChoiceGroup.MULTIPLE,ep,null);//Passenger Info items
passCNT = new ChoiceGroup("Number of Passengers:",ChoiceGroup.POPUP,count,null);
rDate = new DateField("Return Date",DateField.DATE_TIME);//Could not get the DateField to return string date value
dDate = new DateField("Departure Date",DateField.DATE_TIME);
Eneed = new TextField("Special Needs","",50,TextField.ANY);
uName = new TextField("User Name","",5,TextField.ANY);
uName2 = new TextField("User Name","",5,TextField.ANY);
info = new Command("Next",Command.SCREEN,2);
AiC = new Command("Complete",Command.SCREEN,2);//Air travel option items
airT = new ChoiceGroup("Choose Airline", ChoiceGroup.POPUP,AL,null);//Airline selection
airC = new ChoiceGroup("Select Class",ChoiceGroup.EXCLUSIVE);//Economy or first cass?
airC.append("First Class", null);//Adding elements to Choice Group
airC.append("Economy", null);
AuC = new ChoiceGroup("Choose rental company", ChoiceGroup.POPUP,Rental,null);//Auto travel option items
AuT = new ChoiceGroup("Select Vehicle Type", ChoiceGroup.EXCLUSIVE, CT,null);//Choicegroup for Vehicle type
AutC = new Command("Drive away", Command.SCREEN,2);//Adding drive away command to form
CrL = new ChoiceGroup("Select Cruise Line Comp.", ChoiceGroup.POPUP,CL,null);//Cruise option Items, Cruise line choicegroup
CcabT = new ChoiceGroup("Select Cabin Type", ChoiceGroup.EXCLUSIVE,Cabin,null);//Cabin type choice group
CrC = new Command("Cruise", Command.SCREEN,2);//Cruise form command being added
trainC = new Command("Track!", Command.SCREEN,2);//Train option items, Train form command
Tseat = new ChoiceGroup("Seat Type", ChoiceGroup.EXCLUSIVE,tCAB,null);//Choicegroup for train seat type
TOP = new ChoiceGroup("Extra Options", ChoiceGroup.POPUP,Toptions,null);//Train extra options choice group
/* Appending Items to necessary Forms*/
create.append(uName2);
create.addCommand(createC);
create.setCommandListener(this);
home.addCommand(prev);
home.addCommand(newTrip);
home.setCommandListener(this);
login.append(uName);
login.addCommand(logC);
login.addCommand(signC);
login.setCommandListener(this);
startForm.append(trans);
startForm.addCommand(Exit);
startForm.addCommand(Trip);
startForm.setCommandListener(this);
Pass.append(dDate);
Pass.append(rDate);
Pass.append(hCAP);
Pass.append(passCNT);
Pass.append(Eneed);
Pass.addCommand(info);
Pass.setCommandListener(this);
airForm.append(airT);
airForm.append(airC);
airForm.addCommand(AiC);
airForm.setCommandListener(this);
autoForm.addCommand(AutC);
autoForm.append(AuC);
autoForm.append(AuT);
autoForm.setCommandListener(this);
cruiseForm.addCommand(CrC);
cruiseForm.append(CrL);
cruiseForm.append(CcabT);
cruiseForm.setCommandListener(this);
trainForm.addCommand(trainC);
trainForm.append(Tseat);
trainForm.append(TOP);
trainForm.setCommandListener(this);
Ext.addCommand(Exit);
Ext.addCommand(Home);
Ext.setCommandListener(this);
}
public void startApp() {
Xdisplay= Display.getDisplay(this);
Xdisplay.setCurrent(login);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable displayable){
try {
usr = RecordStore.openRecordStore(USERS, false);
} catch (Exception e) {
Sucess = new Alert("Error","Could not open Record Strore",null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
if(c==signC)
{
Xdisplay.setCurrent(create);
}
else if(c == newTrip)
{
Xdisplay.setCurrent(startForm);
}
else if(c == prev)
{
try {
String record = "";
for (int i = 1; i < usr.getNextRecordID(); i++) {
record = new String(usr.getRecord(i));
}
home.append(record);
} catch (Exception e) {
home.append("Could not retrieve data");
try {
usr.closeRecordStore();
RecordStore.deleteRecordStore(USERS);
} catch (Exception x) {
}
}
try {
usr.closeRecordStore();
} catch (Exception e) {
}
}
else if(c==createC)
{
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
if(!"".equals(uName2.getString()))
{
writeRecord(uName2.getString());
}
Sucess = new Alert("Welcome to the mile high club","Hello:"+uName2.getString(),null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
else if (c == logC)
{
if(!"".equals(uName.getString()))
{
String name = uName.getString();
byte[] data = name.getBytes();
Xdisplay.setCurrent(home);
}
else
{
Sucess = new Alert("Please enter user name!","Invalid user name",null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
}
else if(c==Trip)
{
tt +="Travel Mode: "+ trans.getString(trans.getSelectedIndex())+"\n";
if(trans.isSelected(0))
{
TT="A"; //Sets the type of travel based on choicegroup user selection
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(1))
{
TT="B";
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(2))
{
TT="C";
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(3))
{
TT="D";
Xdisplay.setCurrent(Pass);
}
}
else if (c == info)
{
for(int i = 0; i < hCAP.size(); i++) //Checks to see what items are selected in a ChoiceGrou
{
if(hCAP.isSelected(i))
{
details += hCAP.getString(i)+","; //If item is selected then it is appended to the string details
}
}
Rdate = rDate.getDate().toString();
Ddate = dDate.getDate().toString();
tt+= "Departure Date: "+ Ddate.substring(0, 10)+"\n";
tt+= "Return Date: "+ Rdate.substring(0, 10)+"\n";
Pcount = passCNT.getString(passCNT.getSelectedIndex()); //Gets passenger count from choicegroup of integers
specialA = Eneed.getString();
Final = new Alert("Your travel details: \n","Requested Devices:"+details+"\nPassenger Count: "+Pcount+
"\nSpecific Request: "+specialA,null,AlertType.INFO); //Appends string for alert
Final.setTimeout(Alert.FOREVER);
if("A".equals(TT)){ //Directs user to form based on travel type choice
Xdisplay.setCurrent(Final,airForm);
}
else if("B".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, autoForm);
}
else if ("C".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, cruiseForm);
}
else if ("D".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, trainForm);
}
}
else if(c==AiC)
{
AIR = airT.getString(airT.getSelectedIndex());//Retrieves selected item from choicegroup
tt+="Company: "+AIR+"\n";
AIR2 = airC.getString(airC.getSelectedIndex());//Retrieves selected item from choicegroup
FinalT = new Alert("Flight Details: \n","Airline Company:"+AIR+"\nSeat Class: "+AIR2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Airline Carrier: "+AIR+"\nSeat Type: "+AIR2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT,Ext);
}
else if (c == AutC)
{
AUTO = AuC.getString(AuC.getSelectedIndex());//Retrieves selected item from choicegroup
tt += "Company: "+AUTO+"\n";
AUTO2 = AuT.getString(AuT.getSelectedIndex());//Retrieves selected item from choicegroup
FinalT = new Alert("Auto Details: \n","Car Rental Company:"+AUTO+"\nVehicle Class: "+AUTO2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Rental Company: "+AUTO+"\nVehicle Class: "+AUTO2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if (c == CrC)
{
CRUISE = CrL.getString(CrL.getSelectedIndex());
tt += "Company: "+CRUISE+"\n";
CRUISE2 = CcabT.getString(CcabT.getSelectedIndex());
FinalT = new Alert("Cruise Details: \n","Cruise Line Company:"+CRUISE+"\nCabin Type:"+CRUISE2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Cruise Line Company: "+CRUISE+"\nCabin Type: "+CRUISE2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if (c == trainC)
{
TRAIN = Tseat.getString(Tseat.getSelectedIndex());
TRAIN2 = TOP.getString(TOP.getSelectedIndex());
FinalT = new Alert("Train Details: \n","Train Seat Type:"+TRAIN+"\nExtra Amenities:"+TRAIN2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Train Seat Type: "+TRAIN+"\nExtra Amenities: "+TRAIN2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if(c == Home)
{
home.deleteAll();
Xdisplay.setCurrent(login);
}
else if(c==Exit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

Validation in swt text

I would like to validate numbers input in text box.
I want the user to input only integer, decimal in the box between a maximum and minimum values.
How can I make sure of this?
Thank you.
Use a VerifyListener as this will handle paste, backspace, replace.....
E.g.
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
You can register a ModifyListener with the text control and use it to validate the number.
txt.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent event) {
String txt = ((Text) event.getSource()).getText();
try {
int num = Integer.parseInt(txt);
// Checks on num
} catch (NumberFormatException e) {
// Show error
}
}
});
You could also use addVerifyListener to prevent certain characters being entered. In the event passed into that method there is a "doit" field. If you set that to false it prevents the current edit.
Integer validation in SWT
text = new Text(this, SWT.BORDER);
text.setLayoutData(gridData);
s=text.getText();
this.setLayout(new GridLayout());
text.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
e.doit = false;
return;
}
}
}
});
If you only want to allow Integer values you could use a Spinner instead of a text field.
For the validation of Double values you have to consider that characters like E may be included in Doubles and that partial input like "4e-" should be valid while typing. Such partial expressions will give a NumberFormatException for Double.parseDouble(partialExpression)
Also see my answer at following related question:
How to set a Mask to a SWT Text to only allow Decimals
1.create a utill class implement verify listener
2.override verifytext method
3.implement your logic
4.create a object of utill class where you want to use verify listener (on text)
5.text.addverifylistener(utillclassobject)
Example :-
1. utill class:-
public class UtillVerifyListener implements VerifyListener {
#Override
public void verifyText(VerifyEvent e) {
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
2.use of verifylistener in other class
public class TestVerifyListenerOne {
public void createContents(Composite parent){
UtillVerifyListener listener=new UtillVerifyListener();
textOne = new Text(composite, SWT.BORDER);
textOne .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textOne .addVerifyListener(listener)
textTwo = new Text(composite, SWT.BORDER);
textTwo .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textTwo .addVerifyListener(listener);
}
}
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
Text text = (Text) e.getSource();
final String oldS = text.getText();
String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
boolean isValid = true;
try {
if(! "".equals(newS)){
Float.parseFloat(newS);
}
} catch (NumberFormatException ex) {
isValid = false;
}
e.doit = isValid;
}
});

save data from servlet to recordstore in j2me

I am developing an j2me application which is communicating with the database using servlet.
I want to store the data received from servlet into record store and display it.how this can be achieved?Please provide code examples.
Thank you in advance
public void viewcon()
{
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os = (DataOutputStream)c.openDataOutputStream();
os.flush();
os.close();
// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
// return sb;
showAlert(sb.toString());//display data received from servlet
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
Put this function call where you show the response data alert
writeToRecordStore(sb.toString().getBytes());
The function definition is as below:
private static String RMS_NAME = "NETWORK-DATA-STORAGE";
private boolean writeToRecordStore(byte[] inStream) {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore(RMS_NAME, true);
if (null != rs) {
//Based on your logic either ADD or SET the record
rs.addRecord(inStream, 0, inStream.length);
return true;
} else {
return false;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
} finally {
try {
if (null != rs) {
rs.closeRecordStore();
}
} catch (RecordStoreException recordStoreException) {
} finally {
rs = null;
}
}
}
After you have saved the data, read the records store RMS-NAME and check the added index to get the response data.
.
NOTE: The assumption is the network response data is to be appended to the record store. If you want to set it to a particular record modify the method writeToRecordStore(...) accordingly.
//this code throws exception in display class.
try
{
byte[] byteInputData = new byte[5];
int length = 0;
// access all records present in record store
for (int x = 1; x <= rs.getNumRecords(); x++)
{
if (rs.getRecordSize(x) > byteInputData.length)
{
byteInputData = new byte[rs.getRecordSize(x)];
}
length = rs.getRecord(x, byteInputData, 0);
}
alert =new Alert("reading",new String(byteInputData,0,length),null,AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}

SD Card's Free Size

I want to check the free size available on My Device's SD Card. I know FileConnection API. How can I check the free size of the SD Card ?
The idea is to open the cfcard file connection and call availableSize() on it. to get the proper memory card location read it from the System.getProperty(...). In some devices the aforesaid property may fail hence constructing new path from the memory card name system property.
NOTE: In certain devices the hostname must be 'localhost', hence change the return string in getFilehost() appropriately.
PS: Since this is a code snippet certain form / command references may throw null pointer please resolve it accordingly.
Below code with get you the available size in 'BYTES' of the memory card
String memoryCardPath = System.getProperty("fileconn.dir.memorycard");
addToLogs(memoryCardPath);
if (null == memoryCardPath) {
displayAlert(null);
}
nativeHostname(memoryCardPath);
addToLogs(nativeHostname);
String path = buildPath(memoryCardPath.substring(getFilehost().length()));
addToLogs(path);
long availableSize = getAvailableSize(path);
addToLogs(String.valueOf(availableSize)+" Bytes");
if(availableSize == 0L) {
String memoryCardName = System.getProperty("fileconn.dir.memorycard.name");
addToLogs(memoryCardName);
path = buildPath(memoryCardName + "/");
addToLogs(path);
availableSize = getAvailableSize(path);
addToLogs(String.valueOf(availableSize)+" Bytes");
if(availableSize == 0L) {
displayAlert(null);
return;
}
}
displayAlert(String.valueOf(availableSize));
Supporting methods
public String buildPath(String foldername) {
if(null == foldername) {
foldername = "";
}
addToLogs("[BP]"+getFilehost());
addToLogs("[BP]"+foldername);
return new StringBuffer().append(getFilehost()).append(foldername).toString();
}
String nativeHostname = null;
public void nativeHostname(String url) {
String host = url.substring("file://".length());
addToLogs("[NH]"+host);
int index = host.indexOf('/');
addToLogs("[NH]"+String.valueOf(index));
if(index > 0) {
nativeHostname = host.substring(0, index);
} else {
nativeHostname = "/";
}
addToLogs("[NH]"+nativeHostname);
}
public boolean tryLocalhost = false;
public String getFilehost() {
final StringBuffer buf = new StringBuffer().append("file://");
if (null != nativeHostname && nativeHostname.length() > 0) {
buf.append(nativeHostname);
}
addToLogs("[GFH] "+buf.toString());
return buf.toString();
}
public long getAvailableSize(String path) {
FileConnection fcon = null;
try {
fcon = (FileConnection) Connector.open(path, Connector.READ);
if(null != fcon && fcon.exists()) {
return fcon.availableSize();
} else {
return 0L;
}
} catch (IOException ex) {
ex.printStackTrace();
addToLogs("[GAS]"+"ERROR : "+ex.getMessage());
return 0L;
} finally {
try {
fcon.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void displayAlert(String text) {
Alert alert = new Alert(
null == text ? "Warning" : "Info",
null == text ? "Memory card not available" : text,
null,
null == text ? AlertType.WARNING : AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
Display.getDisplay(this).setCurrent(alert, Display.getDisplay(this).getCurrent());
}
public void addToLogs(String log) {
log = null == log ? "null" : log;
getFormLogs().append(new StringItem("", log+"\n"));
}

Resources