CODING OF J2ME APPLICATION:-
CONTACTS:-
AddressBook Coding:-
import java.io.EOFException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.Enumeration;import java.util.Vector;
import javax.microedition.io.Connector;import javax.microedition.io.HttpConnection;import javax.microedition.lcdui.Alert;import javax.microedition.lcdui.AlertType;import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;import javax.microedition.lcdui.Command;import javax.microedition.lcdui.CommandListener;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Displayable;import javax.microedition.lcdui.Form;import javax.microedition.lcdui.Item;import javax.microedition.lcdui.ItemStateListener;import javax.microedition.lcdui.List;import javax.microedition.lcdui.Screen;import javax.microedition.lcdui.TextBox;import javax.microedition.lcdui.TextField;import javax.microedition.midlet.MIDlet;import javax.microedition.rms.RecordComparator;import javax.microedition.rms.RecordEnumeration;import javax.microedition.rms.RecordFilter;import javax.microedition.rms.RecordStore;import javax.microedition.rms.RecordStoreException;
public class AddressBookMIDlet extends MIDlet implements CommandListener, ItemStateListener {
private RecordStore addrBook;
private static final int FN_LEN = 10;
private static final int LN_LEN = 20;
private static final int PN_LEN = 15;
final private static int ERROR = 0;
final private static int INFO = 1;
private Display display;
private Alert alert;
private Command cmdAdd;
private Command cmdBack;
private Command cmdCancel;
private Command cmdDial;
private Command cmdExit;
private Command cmdSelect;
private Command cmdSearchNetwork;
private Command cmdSearchLocal;
private List mainScr;
private String[] mainScrChoices = { "Search", "Add New", "Browse", "Options" };
private Form searchScr;
private TextField s_lastName;
private TextField s_firstName;
private Form entryScr;
private TextField e_lastName;
private TextField e_firstName;
private TextField e_phoneNum;
private List nameScr;
private Vector phoneNums;
private Form optionScr;
private ChoiceGroup sortChoice;
private TextBox dialScr;
private int sortOrder = 1; public AddressBookMIDlet() { display = Display.getDisplay(this);
cmdAdd = new Command("Add", Command.OK, 1); cmdBack = new Command("Back", Command.BACK, 2); cmdCancel = new Command("Cancel", Command.BACK, 2); cmdDial = new Command("Dial", Command.OK, 1); cmdExit = new Command("Exit", Command.EXIT, 2); cmdSelect = new Command("Select", Command.OK, 1); cmdSearchNetwork = new Command("Network", Command.SCREEN, 4); cmdSearchLocal = new Command("Local", Command.SCREEN, 3);
alert = new Alert("", "", null, AlertType.INFO); alert.setTimeout(2000);
try { addrBook = RecordStore.openRecordStore("TheAddressBook", true); } catch (RecordStoreException e) { addrBook = null; } }
protected void startApp() { if (addrBook == null) { displayAlert(ERROR, "Could not open address book", null); } else { genMainScr(); } }
protected void pauseApp() { }
protected void destroyApp(boolean unconditional) { if (addrBook != null) { try { addrBook.closeRecordStore(); } catch (Exception e) { } } }
private void displayAlert(int type, String msg, Screen s) { alert.setString(msg);
switch (type) { case ERROR: alert.setTitle("Error!"); alert.setType(AlertType.ERROR); break; case INFO: alert.setTitle("Info"); alert.setType(AlertType.INFO); break; } display.setCurrent(alert, s == null ? display.getCurrent() : s); }
private void midletExit() { destroyApp(false); notifyDestroyed(); }
private Screen genMainScr() { if (mainScr == null) { mainScr = new List("Menu", List.IMPLICIT, mainScrChoices, null); mainScr.addCommand(cmdSelect); mainScr.addCommand(cmdExit); mainScr.setCommandListener(this); } display.setCurrent(mainScr); return mainScr;
}
private Screen genOptionScr() { if (optionScr == null) { optionScr = new Form("Options"); optionScr.addCommand(cmdBack); optionScr.setCommandListener(this);
sortChoice = new ChoiceGroup("Sort by", Choice.EXCLUSIVE); sortChoice.append("First name", null); sortChoice.append("Last name", null); sortChoice.setSelectedIndex(sortOrder, true); optionScr.append(sortChoice); optionScr.setItemStateListener(this); } display.setCurrent(optionScr); return optionScr; }
private Screen genSearchScr() { if (searchScr == null) { searchScr = new Form("Search"); searchScr.addCommand(cmdBack); searchScr.addCommand(cmdSearchNetwork); searchScr.addCommand(cmdSearchLocal); searchScr.setCommandListener(this); s_firstName = new TextField("First name:", "", FN_LEN, TextField.ANY); s_lastName = new TextField("Last name:", "", LN_LEN, TextField.ANY); searchScr.append(s_firstName); searchScr.append(s_lastName); }
s_firstName.delete(0, s_firstName.size()); s_lastName.delete(0, s_lastName.size()); display.setCurrent(searchScr); return searchScr;
}
private Screen genEntryScr() { if (entryScr == null) { entryScr = new Form("Add new"); entryScr.addCommand(cmdCancel); entryScr.addCommand(cmdAdd); entryScr.setCommandListener(this);
e_firstName = new TextField("First name:", "", FN_LEN, TextField.ANY); e_lastName = new TextField("Last name:", "", LN_LEN, TextField.ANY); e_phoneNum = new TextField("Phone Number", "", PN_LEN, TextField.PHONENUMBER); entryScr.append(e_firstName); entryScr.append(e_lastName); entryScr.append(e_phoneNum); }
e_firstName.delete(0, e_firstName.size()); e_lastName.delete(0, e_lastName.size()); e_phoneNum.delete(0, e_phoneNum.size());
display.setCurrent(entryScr); return entryScr; }
private Screen genNameScr(String title, String f, String l, boolean local) { SimpleComparator sc; SimpleFilter sf = null; RecordEnumeration re; phoneNums = null;
if (local) { sc = new SimpleComparator( sortOrder == 0 ? SimpleComparator.SORT_BY_FIRST_NAME : SimpleComparator.SORT_BY_LAST_NAME);
if (f != null || l != null) { sf = new SimpleFilter(f, l); }
try { re = addrBook.enumerateRecords(sf, sc, false); } catch (Exception e) { displayAlert(ERROR, "Could not create enumeration: " + e, null); return null; } } else { re = new NetworkQuery(f, l, sortOrder); }
nameScr = null; if (re.hasNextElement()) { nameScr = new List(title, List.IMPLICIT); nameScr.addCommand(cmdBack); nameScr.addCommand(cmdDial); nameScr.setCommandListener(this); phoneNums = new Vector(6);
try { while (re.hasNextElement()) { byte[] b = re.nextRecord(); String pn = SimpleRecord.getPhoneNum(b); nameScr.append(SimpleRecord.getFirstName(b) + " " + SimpleRecord.getLastName(b) + " " + SimpleRecord.getPhoneNum(b), null); phoneNums.addElement(pn); } } catch (Exception e) { displayAlert(ERROR, "Error while building name list: " + e, null); return null; } display.setCurrent(nameScr);
} else { displayAlert(INFO, "No names found", null);
}
return nameScr; }
private void genDialScr() { dialScr = new TextBox("Dialing", (String) phoneNums.elementAt(nameScr .getSelectedIndex()), PN_LEN, TextField.PHONENUMBER); dialScr.addCommand(cmdCancel); dialScr.setCommandListener(this); display.setCurrent(dialScr); }
private void addEntry() { String f = e_firstName.getString(); String l = e_lastName.getString(); String p = e_phoneNum.getString();
byte[] b = SimpleRecord.createRecord(f, l, p); try { addrBook.addRecord(b, 0, b.length); displayAlert(INFO, "Record added", mainScr); } catch (RecordStoreException rse) { displayAlert(ERROR, "Could not add record" + rse, mainScr); } }
public void commandAction(Command c, Displayable d) { if (d == mainScr) { // Handle main sceen if (c == cmdExit) { midletExit(); // exit } else if ((c == List.SELECT_COMMAND) || (c == cmdSelect)) { switch (mainScr.getSelectedIndex()) { case 0: // display search screen
genSearchScr(); break; case 1: // display name entry screen genEntryScr(); break; case 2: // display all names genNameScr("Browse", null, null, true); break; case 3: // display option screen genOptionScr(); break; default: displayAlert(ERROR, "Unexpected index!", mainScr); } } } else if (d == nameScr) { // Handle a screen with names displayed, either // from a browse or a search if (c == cmdBack) { // display main screen genMainScr(); } else if (c == cmdDial) { // dial the phone screen genDialScr(); } } else if (d == entryScr) { // Handle the name entry screen if (c == cmdCancel) { // display main screen genMainScr(); } else if (c == cmdAdd) { // display name entry screen addEntry(); } } else if (d == optionScr) { // Handle the option screen if (c == cmdBack) {
// display main screen genMainScr(); } } else if (d == searchScr) { // Handle the search screen if (c == cmdBack) { // display main screen genMainScr(); } else if (c == cmdSearchNetwork || c == cmdSearchLocal) {
// display search of local addr book genNameScr("Search Result", s_firstName.getString(), s_lastName .getString(), c == cmdSearchLocal); } } else if (d == dialScr) { if (c == cmdCancel) { // display main screen genMainScr(); } } }
public void itemStateChanged(Item item) { if (item == sortChoice) { sortOrder = sortChoice.getSelectedIndex(); } }}
class NetworkQuery implements RecordEnumeration { private StringBuffer buffer = new StringBuffer(60);
private String[] fields = new String[3];
private String empty = new String();
private Vector results = new Vector(20);
private Enumeration resultsEnumeration;
final static String baseurl = "http://127.0.0.1:8080/Book/netaddr";
NetworkQuery(String firstname, String lastname, int sortorder) { HttpConnection c = null; int ch; InputStream is = null; InputStreamReader reader; String url;
// Format the complete URL to request buffer.setLength(0); buffer.append(baseurl); buffer.append("?last="); buffer.append((lastname != null) ? lastname : empty); buffer.append("&first="); buffer.append((firstname != null) ? firstname : empty); buffer.append("&sort=" + sortorder);
url = buffer.toString();
// Open the connection to the service try { c = open(url); results.removeAllElements();
is = c.openInputStream(); reader = new InputStreamReader(is); while (true) { int i = 0; fields[0] = empty; fields[1] = empty; fields[2] = empty; do { buffer.setLength(0); while ((ch = reader.read()) != -1 && (ch != ',') && (ch != '\n')) { if (ch == '\r') { continue; }
buffer.append((char) ch); }
if (ch == -1) { throw new EOFException(); }
if (buffer.length() > 0) { if (i < fields.length) { fields[i++] = buffer.toString(); } } } while (ch != '\n');
if (fields[0].length() > 0) { results.addElement(SimpleRecord.createRecord(fields[0], fields[1], fields[2])); } } } catch (Exception e) {
} finally { try { if (is != null) { is.close(); } if (c != null) { c.close(); } } catch (Exception e) { } } resultsEnumeration = results.elements(); }
private HttpConnection open(String url) throws IOException { HttpConnection c; int status = -1;
// Open the connection and check for redirects
while (true) { c = (HttpConnection) Connector.open(url); status = c.getResponseCode();
if ((status == HttpConnection.HTTP_TEMP_REDIRECT) || (status == HttpConnection.HTTP_MOVED_TEMP) || (status == HttpConnection.HTTP_MOVED_PERM)) {
// Get the new location and close the connection url = c.getHeaderField("location"); c.close(); } else { break; } }
// Only HTTP_OK (200) means the content is returned. if (status != HttpConnection.HTTP_OK) { c.close(); throw new IOException("Response status not OK"); } return c; }
public boolean hasNextElement() { return resultsEnumeration.hasMoreElements(); }
public byte[] nextRecord() { return (byte[]) resultsEnumeration.nextElement(); }
public boolean hasPreviousElement() { return false; }
public void destroy() { }
public boolean isKeptUpdated() {
return false; }
public void keepUpdated(boolean b) { return; }
public int nextRecordId() { return 0; }
public int numRecords() { return 0; }
public byte[] previousRecord() { return null; }
public int previousRecordId() { return 0; }
public void rebuild() { return; }
public void reset() { return; }}
class SimpleFilter implements RecordFilter { private String first; private String last;
public SimpleFilter(String f, String l) { first = f.toLowerCase(); last = l.toLowerCase(); }
public boolean matches(byte[] r) {
String f = SimpleRecord.getFirstName(r).toLowerCase(); String l = SimpleRecord.getLastName(r).toLowerCase(); return f.startsWith(first) && l.startsWith(last); }}
class SimpleComparator implements RecordComparator { public final static int SORT_BY_FIRST_NAME = 1;
public final static int SORT_BY_LAST_NAME = 2;
private int sortOrder = -1; SimpleComparator(int s) { switch (s) { case SORT_BY_FIRST_NAME: case SORT_BY_LAST_NAME: this.sortOrder = s; break; default: this.sortOrder = SORT_BY_LAST_NAME; break; } }
public int compare(byte[] r1, byte[] r2) {
String n1 = null; String n2 = null;
if (sortOrder == SORT_BY_FIRST_NAME) { n1 = SimpleRecord.getFirstName(r1).toLowerCase(); n2 = SimpleRecord.getFirstName(r2).toLowerCase(); } else if (sortOrder == SORT_BY_LAST_NAME) { n1 = SimpleRecord.getLastName(r1).toLowerCase(); n2 = SimpleRecord.getLastName(r2).toLowerCase(); }
int n = n1.compareTo(n2); if (n < 0) { return RecordComparator.PRECEDES; } if (n > 0) { return RecordComparator.FOLLOWS; }
return RecordComparator.EQUIVALENT; }}
final class SimpleRecord {
private final static int FIRST_NAME_INDEX = 0; private final static int LAST_NAME_INDEX = 20; private final static int FIELD_LEN = 20; private final static int PHONE_INDEX = 40; private final static int MAX_REC_LEN = 60; private static StringBuffer recBuf = new StringBuffer(MAX_REC_LEN); private SimpleRecord() { }
private static void clearBuf() { for (int i = 0; i < MAX_REC_LEN; i++) { recBuf.insert(i, ' '); } recBuf.setLength(MAX_REC_LEN); }
public static byte[] createRecord(String first, String last, String num) { clearBuf(); recBuf.insert(FIRST_NAME_INDEX, first); recBuf.insert(LAST_NAME_INDEX, last); recBuf.insert(PHONE_INDEX, num); recBuf.setLength(MAX_REC_LEN); return recBuf.toString().getBytes(); }
public static String getFirstName(byte[] b) {
return new String(b, FIRST_NAME_INDEX, FIELD_LEN).trim(); }
public static String getLastName(byte[] b) { return new String(b, LAST_NAME_INDEX, FIELD_LEN).trim(); }public static String getPhoneNum(byte[] b) { return new String(b, PHONE_INDEX, FIELD_LEN).trim(); }}
ANSWER.COM:-
AuthenticationMidlet.java coding:-
import javax.microedition.midlet.*;import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Displayable;
public class AuthenticationMidlet extends MIDlet { public static AuthenticationMidlet instance; MM displayable; public static String SERVER_URL = null;
/** Constructor */ public AuthenticationMidlet() { instance = this; //Read From JAD File if there are any parameters SERVER_URL = getAppProperty("URL"); }
/** Main method */ public void startApp() { try{ displayable = new MM();// Display.getDisplay(this).setCurrent(displayable); }catch(Exception e){ e.printStackTrace(); } }
/** Handle pausing the MIDlet */ public void pauseApp() {
}
/** Handle destroying the MIDlet */ public void destroyApp(boolean unconditional) { }
/** Quit the MIDlet */ public static void quitApp() { instance.destroyApp(true); instance.notifyDestroyed(); instance = null; }
}
MM.java Coding:-
import java.util.Vector;import java.util.Enumeration;
import javax.microedition.lcdui.*;import javax.microedition.lcdui.Form;import javax.microedition.lcdui.List;import javax.microedition.lcdui.Alert;import javax.microedition.lcdui.TextBox;import javax.microedition.lcdui.StringItem;import javax.microedition.rms.*;import java.io.*;import javax.microedition.io.*;import javax.microedition.lcdui.Command;import javax.microedition.lcdui.CommandListener;
class MM extends Form implements CommandListener, Runnable {
Command CMDLogin,CMDEXIT,CMDEXITMain, CMDREQ, CMDNext, CMDShowQ, backToMain,help; int i = 0; public static final int CMD_LOGIN = 1; public static final int CMD_REQ_Course = 2;
private static final int LOGIN = 0; private static final int NEXT_Q = 1;
private List regMenu, historyList; private Form LoginScreen; private String password,loginName;
//DataBase; RecordStore rs = null;
String rs_saved = "0"; // default not saved String rs_id = ""; String rs_pass = ""; public int opr = 0; private TextField login_txt, password_txt;
private ChoiceGroup login_save = null; public static Object lock;
private Vector list = null;
private static int currentSelection = 0;// // private Enumeration enum;
public boolean inRequest = false;
private final long TIMEOUT_PERIOD = 60000L; public static long timeout = 0L;
private HttpConnection mHttpConnection; private InputStream is = null; private OutputStream os = null; private String CommandType = null;
private StringBuffer sb = null; private int count = 0; private int requestType = 0; private String serverResponse = null; Form mainMenu = null; Thread thrd = null;
public String question [][]= {{"Adolf Hitler. Date of Birth:"," April 14,1889 "},{"Abraham Lincoln's Date Of Birth is ","On February 12, 1892 "},{"Mahatama ganshi date of birth","October 2,1889" },{"Maharaja ranjeet singh's Capital","Lahore"}}; TextBox qScreen = null;
/** Constructor */ public MM() throws Exception{ super("**Login**"); //Lock is initialized. lock = new Object(); //Initializing a thread. thrd = new Thread(this);
record(/*LOAD*/2);
login_txt = new TextField("Login_Name",rs_id,25,TextField.ANY); this.append(login_txt); password_txt = new TextField("password",rs_pass,25,TextField.PASSWORD); this.append(password_txt); login_save = null; login_save = new ChoiceGroup("",ChoiceGroup.MULTIPLE);
login_save.append("Save Login",null);this.append(login_save);
CMDLogin = new Command("Send",Command.SCREEN,1);this.addCommand(CMDLogin);
this.setCommandListener(this);
LoginScreen = this;
Display.getDisplay(AuthenticationMidlet.instance).setCurrent(this); }
public void record(int opr){ byte[] rs_id_b = " ".getBytes(); byte[] rs_pass_b = " ".getBytes(); try{
rs = RecordStore.openRecordStore("History.DB",true); // create/open if necessay.
int numRecords = rs.getNumRecords();
if (numRecords == 0) {// save the default settings.
// rs.addRecord(rs_saved_b,0,rs_saved_b.length);rs_id_b = login_txt.getString().getBytes();rs_pass_b = password_txt.getString().getBytes();
rs.addRecord(rs_id_b,0,rs_id_b.length);rs.addRecord(rs_pass_b,0,rs_pass_b.length);
}
if ((opr == /*SAVE*/1)) {rs_id_b = login_txt.getString().getBytes();rs_pass_b = password_txt.getString().getBytes();
rs.setRecord(1,rs_id_b,0,rs_id_b.length);rs.setRecord(2,rs_pass_b,0,rs_pass_b.length);
} else if (opr == /*LOAD*/2) {
if (rs.getRecord(1) != null) rs_id = new String(rs.getRecord(1)); if (rs.getRecord(2) != null) rs_pass = new String(rs.getRecord(2));
}
rs.closeRecordStore();}catch(Exception e){}
}
private void showMainMenu(String str){ mainMenu = new Form("MainManu");
if(str.equals("true")){ mainMenu.append("You are authenticated user"); CMDEXITMain = new Command("OK",Command.OK,1); CMDREQ = new Command("EXIT",Command.EXIT,1);
mainMenu.addCommand(CMDEXITMain); mainMenu.addCommand(CMDREQ); }else{
mainMenu.append("Sorry you are not an authenticated user"); CMDEXITMain = new Command("Exit",Command.EXIT,1); mainMenu.addCommand(CMDEXITMain);
}
mainMenu.setCommandListener(this); Display.getDisplay(AuthenticationMidlet.instance).setCurrent(mainMenu); }
private void showServicesScreen(){ try{ historyList = new List("Select History",List.IMPLICIT);
historyList.append("1. Indian History",null); historyList.append("2. Europe",null); historyList.append("3. American History",null); historyList.append("4. History Of Punjab",null);
historyList.setCommandListener(this);
CMDShowQ = new Command("Question",1,Command.OK); CMDEXIT = new Command("Exit",2,Command.EXIT);
historyList.addCommand(CMDShowQ); historyList.addCommand(CMDEXIT); historyList.setCommandListener(this);
Display.getDisplay(AuthenticationMidlet.instance).setCurrent(historyList); }catch(Exception e){ System.out.println("Exception is "+e.getMessage()); } }
private void showAlert(String alert){ Alert alt = new Alert("alert"); alt.setString(alert); alt.setTimeout(30); Display.getDisplay(AuthenticationMidlet.instance).setCurrent(alt); }
private void showWaitScreen(){ Form waitForm = new Form("Wait Form"); waitForm.append("Please Wait..."); Display.getDisplay(AuthenticationMidlet.instance).setCurrent(waitForm); }
private void showQScreen(){ qScreen = new TextBox("History Update","",300,TextField.ANY); qScreen.setString(question[0][0]+question[0][1]); CMDNext = new Command("Next",1,Command.OK); qScreen.addCommand(CMDNext); qScreen.setCommandListener(this);
Display.getDisplay(AuthenticationMidlet.instance).setCurrent(qScreen); }
/**Handle command events*/ public void commandAction(Command c, Displayable disp) { int cmdType = c.getCommandType();
try{
/** @todo Add command handling code */ if (cmdType == Command.EXIT) { AuthenticationMidlet.quitApp(); }
if (c == CMDLogin){ StringBuffer valuesBuffer = new StringBuffer();
valuesBuffer.append(login_txt.getString()+","+password_txt.getString()); sb = valuesBuffer; String val = null; this.showWaitScreen(); //Open RMS connection and save login password in databasees... int sst = login_save.isSelected(0) ? 1 : 0; if (sst == 1) record(/*SAVE*/1); //Starting a thread. thrd.start(); try{ Thread.sleep(3000); }catch(Exception e){} } if(c == CMDEXITMain) { showServicesScreen(); } if(c == CMDShowQ){ showQScreen(); }
if(c == CMDNext){ ++i; switch(i){ case 1:{ qScreen.setString(question[1][0]+question[1][1]);
Display.getDisplay(AuthenticationMidlet.instance).setCurrent(qScreen); break; } case 2:{ qScreen.setString(question[2][0]+question[2][1]);
Display.getDisplay(AuthenticationMidlet.instance).setCurrent(qScreen); break; } case 3:{ qScreen.setString(question[3][0]+question[3][1]);
Display.getDisplay(AuthenticationMidlet.instance).setCurrent(qScreen); break; } } if(i == 4){ i = 0;
Display.getDisplay(AuthenticationMidlet.instance).setCurrent(historyList); }
} if(c == CMDEXIT ){ AuthenticationMidlet.quitApp(); } }catch(Exception e){ System.out.println("Exception is thrown");
e.printStackTrace(); } }
public synchronized String MakeConnection(StringBuffer values, int cnt, int requestType){ StringBuffer sbuffer = null;
try{ mHttpConnection = (HttpConnection) Connector.open(AuthenticationMidlet.SERVER_URL,Connector.READ_WRITE, true);
// Set the request method and headers mHttpConnection.setRequestMethod(HttpConnection.POST); mHttpConnection.setRequestProperty("Content-Type", "text/plain"); mHttpConnection.setRequestProperty("Accept", "*/*"); mHttpConnection.setRequestProperty("Connection", "close");
//Making Request Here.... String xml = makeRequestXML(values, cnt, requestType);
os = mHttpConnection.openOutputStream(); os.write((xml).getBytes()); os.flush(); if (os != null) os.close();
// Going to accept inputConnection ... is = mHttpConnection.openInputStream(); int len = (int) mHttpConnection.getLength(); System.out.println("***\nLength of inpout stream is " + len + "\n***"); byte data[] = new byte[len + 1];
sbuffer = new StringBuffer(); int ch = 0;
while ( (ch = is.read()) != -1) { sbuffer.append( (char) ch); } System.out.println("Value Read is >> " + sbuffer.toString()); }catch(IOException ioe){ ioe.printStackTrace(); }
mHttpConnection = null; is = null; os = null;
try { // if (mHttpConnection != null) mHttpConnection.close(); System.gc(); is = null; mHttpConnection = null; } catch (Exception exp) {} return sbuffer.toString(); }
public void run(){
try { serverResponse = this.MakeConnection(sb, count, requestType); System.out.println ("Server response is >> "+serverResponse); showMainMenu(serverResponse); }catch (Exception e) {e.printStackTrace();} }
private String makeRequestXML(StringBuffer value,int count, int reqType){
String Request_XML = null; switch(reqType){
case LOGIN:{ Request_XML = value.toString(); } }
return Request_XML; } private boolean handleLoginRequest(String requestString){
boolean bool = false;// StringTokenizer tok=new StringTokenizer(requestString,",");// int tokenCount=tok.countTokens();// String[] clientData=new String[tokenCount];// int counter=0;// while(tok.hasMoreElements())// {// clientData[counter]=(String)tok.nextElement();// counter++;// }//
if(clientData[0].equalsIgnoreCase("username")&&clientData[1].equalsIgnoreCase("password")){// bool = true;// } return bool;} }
Authentication_Servlet.java Coding:-
package Authentication;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;import java.util.*; import java.io.BufferedReader;import java.io.InputStreamReader;
//http://127.0.0.1:8080/Echo_Server/servlet/Echo_Servlet
public class Authentication_Servlet extends HttpServlet {
public void init() {}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {PrintWriter out = response.getWriter();out.println("No GETs allowed.");System.out.println ("i AM COMMING HERE AT
LEAST.");}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
InputStream in;OutputStream out;DataInputStream din;
DataOutputStream dout; String authenticate = "true"; //"Kolkata's Eden Gardens gears up for second Indo-Pak Test ";
try{in =(InputStream) request.getInputStream();
out =(OutputStream) response.getOutputStream(); dout = new DataOutputStream(out);
BufferedReader br = new BufferedReader(new InputStreamReader(in)); String requestString="",str=""; while((str=br.readLine())!=null) requestString+=str;
System.out.println ("Request String is >> "+requestString);
boolean login = handleLoginRequest(requestString);
if(login == true){authenticate = "true";
}else{authenticate = "false";
}
System.out.println ("**********\n\nRequest Got From client\n\n**********");
System.out.println ("*************\n\n"+authenticate+"\n\n*************");
byte[] byteArr = authenticate.getBytes();
dout.write(byteArr);
System.out.println ("\n\n **********\n\nauthenticate value is sent..\n\n***************");
} catch (Throwable e) {}finally{
in = null;out = null;din = null;
dout = null;}
}private boolean handleLoginRequest(String requestString){
boolean bool = false;
StringTokenizer tok=new StringTokenizer(requestString,",");
int tokenCount=tok.countTokens(); String[] clientData = new String[tokenCount]; int counter=0; while(tok.hasMoreElements()) {
clientData[counter]=(String)tok.nextElement(); counter++;
} System.out.println ("UserName is >>"+clientData[0]); System.out.println ("Password is >>"+clientData[1]); if(clientData[0].equalsIgnoreCase("username")||
clientData[1].equalsIgnoreCase("password")){ bool = true; } return bool;} }
Juke Box :-
PlayerMIDlet.java Coding:-
import javax.microedition.lcdui.*;import javax.microedition.media.*;import javax.microedition.media.control.*;import javax.microedition.midlet.*;import java.io.*;import javax.microedition.io.*;
public class PlayerMIDlet extends MIDlet implements CommandListener { private Display display; private List lst; private Command start = new Command("Play",Command.SCREEN, 1);
private Command exit = new Command("Exit",Command.EXIT,2); int currentPlaying = -1; //Sound Player object. static Player bbsounds[]; private Player tonePlayer; public PlayerMIDlet(){ display = Display.getDisplay(this); sound_init(); createTonePlayer(); } protected void startApp() {
String[] elements = {"Play >> airhorn.wav","Play >> intro.midi","Play >> TuneSequence"};
lst = new List("Menu", List.IMPLICIT, elements, null); lst.setCommandListener(this); lst.addCommand(start); display.setCurrent(lst);
} private void reset(){ }
protected void pauseApp() { try { if(bbsounds[currentPlaying] != null && bbsounds[currentPlaying].getState() == bbsounds[currentPlaying].STARTED) { bbsounds[currentPlaying].stop(); } else { defplayer(); } }catch(MediaException me) { reset(); } }
protected void destroyApp(boolean unconditional) { lst = null; try { defplayer(); }catch(MediaException me) { } } public void commandAction(Command c , Displayable d){
int index = lst.getSelectedIndex();
System.out.println("Playing Sound .....");if(c == start){ if (index == 0){ sound_play(0); } if(index == 1){ sound_play(1); } if(index == 2){ playTones(); }}
if(c == exit){this.destroyApp(true);
} } void defplayer() throws MediaException { try{
if (bbsounds[currentPlaying] != null) { if(bbsounds[currentPlaying].getState() ==
bbsounds[currentPlaying].STARTED) {
bbsounds[currentPlaying].stop(); } if(bbsounds[currentPlaying].getState() ==
bbsounds[currentPlaying].PREFETCHED) { bbsounds[currentPlaying].deallocate(); } if(bbsounds[currentPlaying].getState() ==
bbsounds[currentPlaying].REALIZED || bbsounds[currentPlaying].getState() ==
bbsounds[currentPlaying].UNREALIZED) { bbsounds[currentPlaying].close(); } } bbsounds = null;
}catch(Exception e){ } }
public void sound_init(){
try{
bbsounds = new Player[ 3 ];InputStream in =
getClass().getResourceAsStream("airhorn.wav");
try { bbsounds[0] = Manager.createPlayer(in, "audio/X-
wav");}catch( Exception e ){
//System.out.println("Exception in Sound Creation ");
} in = null;
InputStream is = getClass().getResourceAsStream("intro.midi");
try {
bbsounds[1] = Manager.createPlayer(is, "audio/midi");
is = null;
}catch( Exception e ){//System.out.println("Exception in Sound Creation
");}
}catch( Exception e){}}
public void sound_play(int id){
//System.out.println("Playing ID is >>"+id);
sound_stop( currentPlaying );currentPlaying = id;try{
bbsounds[ id ].realize();
System.out.println("Playing Sound...");bbsounds[ id ].start();
}catch(Exception e){//System.out.println("Playing Exception");
}return;
}
public void sound_stop( int id){
try{if(id!=-1){
bbsounds[ id ].deallocate();
bbsounds[ id ].stop();tonePlayer.stop();
}}catch(Exception ex){
//System.out.println("Stop Sound Exception ");}return;
}
private void createTonePlayer() {/**
* "Mary Had A Little Lamb" has "ABAC" structure. * Use block to repeat "A" section. */byte tempo = 30; // set tempo to 120 bpm byte d = 8; // eighth-note
byte C4 = ToneControl.C4;; byte D4 = (byte)(C4 + 2); // a whole step byte E4 = (byte)(C4 + 4); // a major third byte G4 = (byte)(C4 + 7); // a fifth byte rest = ToneControl.SILENCE; // rest
byte[] mySequence = { ToneControl.VERSION, 1, // version 1 ToneControl.TEMPO, tempo, // set tempo ToneControl.BLOCK_START, 0, // start define "A" section E4,d, D4,d, C4,d, E4,d, // content of "A" section E4,d, E4,d, E4,d, rest,d, ToneControl.BLOCK_END, 0, // end define "A" section ToneControl.PLAY_BLOCK, 0, // play "A" section D4,d, D4,d, D4,d, rest,d, // play "B" section E4,d, G4,d, G4,d, rest,d, ToneControl.PLAY_BLOCK, 0, // repeat "A" section D4,d, D4,d, E4,d, D4,d, C4,d // play "C" section};
try{
tonePlayer = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR);
tonePlayer.realize(); ToneControl c =
(ToneControl)tonePlayer.getControl("ToneControl"); c.setSequence(mySequence); } catch (IOException ioe) {System.err.println("Initializing
Tone");} catch (MediaException me) { }
} public void playTones() { if (tonePlayer != null){
try { System.out.println("Playing Sound..."); tonePlayer.prefetch(); tonePlayer.start(); } catch (MediaException me) { //System.err.println("Problem starting player"); } // end catch
} // end if } // end playTone}
Todo:
Coding of Todo Midlet:-
import java.io.*;import java.util.*;import javax.microedition.midlet.*;import javax.microedition.lcdui.*;import javax.microedition.rms.*;
public class TodoMIDlet extends MIDlet implements ItemStateListener, CommandListener{ private Display display; // Our display private Form fmMain; // Main Form private FormAdd fmAdd; // Form to add todo item private Command cmAdd, // Command to add todo
cmPrefs, // Command to set preferences cmExit; // Command to exit private Vector vecTodo; // The "master" list of todo items private ChoiceGroup cgTodo; // Todo items (read from vecTodo) protected DisplayManager displayMgr; // Class to help manage screens
private RecordStore rsTodo; private RecordStore rsPref; private static final String REC_STORE_TODO = "TodoList"; private static final String REC_STORE_PREF = "TodoPrefs"; private boolean flagSortByPriority = false, // Sort by priority? flagShowPriority = true; // Show priorities ?
private ByteArrayInputStream istrmBytes = null; // Read Java data types from the above byte array private DataInputStream istrmDataType = null; // If you change length of a todo entry, bump this byte[] recData = new byte[25];
ByteArrayOutputStream ostrmBytes = null; // Write Java data types into the above byte array DataOutputStream ostrmDataType = null;
private RecordEnumeration e = null; private ComparatorInt comp = null;
public TodoMIDlet() { display = Display.getDisplay(this); fmMain = new Form("Todo List"); fmAdd = new FormAdd("Add Todo", this);
// Todo list and vector cgTodo = new ChoiceGroup("", Choice.MULTIPLE); vecTodo = new Vector();
// Commands cmAdd = new Command("Add Todo", Command.SCREEN, 2);
cmPrefs = new Command("Preferences", Command.SCREEN, 3); cmExit = new Command("Exit", Command.EXIT, 1);
// Add all to form and listen for events fmMain.addCommand(cmAdd); fmMain.addCommand(cmPrefs); fmMain.addCommand(cmExit); fmMain.append(cgTodo); fmMain.setCommandListener(this); fmMain.setItemStateListener(this);
// Create a display manager object displayMgr = new DisplayManager(display, fmMain);
// Open/create the record stores rsTodo = openRecStore(REC_STORE_TODO); rsPref = openRecStore(REC_STORE_PREF);
// Initialize the streams initInputStreams(); initOutputStreams();
// Read preferences from rms refreshPreferences();
// Initialize the enumeration for todo rms initEnumeration();
// Read rms into vector writeRMS2Vector();
// Build the todo list (choice group) rebuildTodoList(); }
public void startApp () { display.setCurrent(fmMain); }
public void destroyApp (boolean unconditional) { // Cleanup for enumerator if (comp != null) comp.compareIntClose(); if (e != null) e.destroy();
// Cleanup streams try { if (istrmDataType != null) istrmDataType.close();
if (istrmBytes != null) istrmBytes.close();
if (ostrmDataType != null) ostrmDataType.close();
if (ostrmBytes != null) ostrmBytes.close(); } catch (Exception e) { db(e.toString()); }
// Cleanup rms closeRecStore(rsTodo); closeRecStore(rsPref); } public void pauseApp () { }
private void initInputStreams() { istrmBytes = new ByteArrayInputStream(recData);
istrmDataType = new DataInputStream(istrmBytes); }
private void initOutputStreams() { ostrmBytes = new ByteArrayOutputStream(); ostrmDataType = new DataOutputStream(ostrmBytes); }
private void initEnumeration() { // Are we to bother with sorting? if (flagSortByPriority) comp = new ComparatorInt(); else // We must set this to null to clear out // any previous setting comp = null;
try { e = rsTodo.enumerateRecords(null, comp, false); } catch (Exception e) { db(e.toString()); } }
private RecordStore openRecStore(String name) { try { // Open the Record Store, creating it if necessary return RecordStore.openRecordStore(name, true); } catch (Exception e) { db(e.toString());
return null; } }
private void closeRecStore(RecordStore rs) { try { rs.closeRecordStore(); } catch (Exception e) { db(e.toString()); } }
private void deleteRecStore(String name) { try { RecordStore.deleteRecordStore(name); } catch (Exception e) { db(e.toString()); } }
protected void addTodoItem(int priority, String text) { try { ostrmBytes.reset();
// Write priority and todo text ostrmDataType.writeInt(priority); ostrmDataType.writeUTF(text);
// Clear any buffered data
ostrmDataType.flush();
// Get stream data into byte array and write record byte[] record = ostrmBytes.toByteArray(); int recordId = rsTodo.addRecord(record, 0, record.length);
// Create a new Todo item and insert it into our Vector TodoItem item = new TodoItem(priority, text, recordId); vecTodo.addElement(item); } catch (Exception e) { db(e.toString()); }
// Read rms into vector writeRMS2Vector();
// Rebuild todo list rebuildTodoList(); }
protected void savePreferences(boolean sort, boolean showSort) { // No changes we made if (sort == flagSortByPriority && showSort == flagShowPriority) return;
// Save the current sort status boolean previouslySorted = flagSortByPriority; boolean previouslyShowPriority = flagShowPriority;
try { // Update prefs in private variables flagSortByPriority = sort; flagShowPriority = showSort; ostrmBytes.reset();
// Write the sort order and keep completed flags ostrmDataType.writeBoolean(flagSortByPriority); ostrmDataType.writeBoolean(flagShowPriority);
// Clear any buffered data ostrmDataType.flush();
// Get stream data into byte array and write record byte[] record = ostrmBytes.toByteArray();
// Always write preferences at first record // We cannot request to set the first record unless // the record store has contents. // If empty => add a record // If not => overwrite the first record if (rsPref.getNumRecords() == 0) rsPref.addRecord(record, 0, record.length); else rsPref.setRecord(1, record, 0, record.length); } catch (Exception e) { db(e.toString()); }
// If the sort order was changed, rebuild enumeration if (previouslySorted != flagSortByPriority) initEnumeration(); if ((!previouslySorted && flagSortByPriority) || (previouslyShowPriority != flagShowPriority)) { // Read rms into vector writeRMS2Vector(); // Rebuild todo list rebuildTodoList(); } }
private void refreshPreferences()
{ try { // Record store is empty if (rsPref.getNumRecords() == 0) { // Write into the store the default preferences savePreferences(flagSortByPriority, flagShowPriority); return; }
// Reset input back to the beginning istrmBytes.reset();
// Read configuration data stored in the first record rsPref.getRecord(1, recData, 0); flagSortByPriority = istrmDataType.readBoolean(); flagShowPriority = istrmDataType.readBoolean();
System.out.println("Sort: " + flagSortByPriority); System.out.println("Show: " + flagShowPriority); } catch (Exception e) { db(e.toString()); } }
private void writeRMS2Vector() { // Cleanout the vector vecTodo.removeAllElements();
try { // Rebuild enumeration for any changes e.rebuild();
while (e.hasNextElement()) {
// Reset input back to the beginning istrmBytes.reset();
// Get data into the byte array int id = e.nextRecordId(); rsTodo.getRecord(id, recData, 0);
// Create a new Todo item and insert it into our Vector TodoItem item = new TodoItem(istrmDataType.readInt(), istrmDataType.readUTF(), id); vecTodo.addElement(item); } } catch (Exception e) { db(e.toString()); } }
private void writeVector2RMS() { try { byte[] record;
for (int i = 0; i < vecTodo.size(); i++) { TodoItem item = (TodoItem) vecTodo.elementAt(i);
int priority = item.getPriority(); String text = item.getText();
ostrmBytes.reset();
// Write priority and todo text ostrmDataType.writeInt(priority); ostrmDataType.writeUTF(text);
// Clear any buffered data ostrmDataType.flush();
// Get stream data into byte array and write record record = ostrmBytes.toByteArray(); rsTodo.addRecord(record, 0, record.length); } } catch (Exception e) { db(e.toString()); } }
protected void rebuildTodoList() { // Clear out the ChoiceGroup. for (int i = cgTodo.size(); i > 0; i--) cgTodo.delete(i - 1);
TodoItem item; int priority; String text; StringBuffer strb;
for (int i = 0; i < vecTodo.size(); i++) { // Get a todo item from vector item = (TodoItem) vecTodo.elementAt(i);
// Read values from todoitem class priority = item.getPriority(); text = item.getText();
// Are we are to show priority as part of the text? strb = new StringBuffer((flagShowPriority ? (Integer.toString(priority) + "-"): "")); strb.append(text);
// Append to todo choicegroup cgTodo.append(strb.toString(), null);
} }
public void itemStateChanged(Item item) { ChoiceGroup cg;
// Cast the item to a ChoiceGroup type cg = (ChoiceGroup) item; for (int i = 0; i < cg.size(); i++) { if (selected[i]) { TodoItem todoitem = (TodoItem) vecTodo.elementAt(i); try { rsTodo.deleteRecord(todoitem.getRecordId()); } catch (Exception e) { db(e.toString()); } break; } } // Read rms into vector writeRMS2Vector(); // Rebuild todo list rebuildTodoList(); }
public void commandAction(Command c, Displayable d) { if (c == cmExit) { destroyApp(false); notifyDestroyed();
} else { if (c == cmAdd) { // Reset the textfield and choicegroup // on the 'add todo' form fmAdd.tfTodo.setString(""); fmAdd.cgPriority.setSelectedIndex(0, true);
// Push current displayable and activate 'add todo' form displayMgr.pushDisplayable(fmAdd); } else if (c == cmPrefs) { boolean flags[] = {flagSortByPriority, flagShowPriority};
// Push current displayable and show preferences form // passing in current preference settings displayMgr.pushDisplayable(new FormPrefs("Preferences", this, flags)); } } }
private void db(String str) { System.err.println("Msg: " + str); }}
class DisplayManager extends Stack{ private Display display; // Reference to Display object private Displayable mainDisplayable; // Main displayable for MIDlet private Alert alStackError; // Alert for error conditions public DisplayManager(Display display, Displayable mainDisplayable) { // Only one display object per midlet, this is it this.display = display;
this.mainDisplayable = mainDisplayable; alStackError = new Alert("Displayable Stack Error"); alStackError.setTimeout(Alert.FOREVER); // Modal }
public void pushDisplayable(Displayable newDisplayable) { push(display.getCurrent()); display.setCurrent(newDisplayable); }
public void home() { while (elementCount > 1) pop(); display.setCurrent(mainDisplayable); } public void popDisplayable() { // If the stack is not empty, pop next displayable if (empty() == false) display.setCurrent((Displayable) pop()); else
display.setCurrent(alStackError, mainDisplayable); }}
class FormAdd extends Form implements CommandListener{ private Command cmBack, cmSave; protected TextField tfTodo; protected ChoiceGroup cgPriority; private TodoMIDlet midlet;
public FormAdd(String title, TodoMIDlet midlet) {
// Call the Form constructor super(title);
this.midlet = midlet;
// Commands cmSave = new Command("Save", Command.SCREEN, 1); cmBack = new Command("Back", Command.BACK, 2);
// Create textfield for entering todo items tfTodo = new TextField("Todo", null, 15, TextField.ANY);
// Create choicegroup and append options (no images) cgPriority = new ChoiceGroup("Priority", Choice.EXCLUSIVE); cgPriority.append("Today", null); cgPriority.append("Tomorrow", null); cgPriority.append("This Week", null); cgPriority.append("This Month", null); cgPriority.append("Someday", null);
// Add stuff to form and listen for events addCommand(cmSave); addCommand(cmBack); append(tfTodo); append(cgPriority); setCommandListener(this); }
public void commandAction(Command c, Displayable s) { if (c == cmSave) { midlet.addTodoItem(cgPriority.getSelectedIndex() + 1, tfTodo.getString()); } midlet.displayMgr.popDisplayable(); }}
class ComparatorInt implements RecordComparator{ private byte[] record = new byte[10];
// Read from a specified byte array private ByteArrayInputStream strmBytes = null;
// Read Java data types from the above byte array private DataInputStream strmDataType = null;
public void compareIntClose() { try { if (strmBytes != null) strmBytes.close(); if (strmDataType != null) strmDataType.close(); } catch (Exception e) {} }
public int compare(byte[] rec1, byte[] rec2) { int x1, x2;
try { // If either record is larger than our buffer, reallocate int maxsize = Math.max(rec1.length, rec2.length); if (maxsize > record.length) record = new byte[maxsize]; strmBytes = new ByteArrayInputStream(rec1); strmDataType = new DataInputStream(strmBytes); x1 = strmDataType.readInt(); strmBytes = new ByteArrayInputStream(rec2); strmDataType = new DataInputStream(strmBytes); x2 = strmDataType.readInt();
if (x1 == x2) return RecordComparator.EQUIVALENT; else if (x1 < x2) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS;
} catch (Exception e) { return RecordComparator.EQUIVALENT; } }}
class TodoItem{ private int priority; private String text; private int recordId;
public TodoItem(int priority, String text, int recordId) { this.priority = priority; this.text = text; this.recordId = recordId; }
public int getPriority() { return priority; }
public void setPriority(int priority) { this.priority = priority; }
public String getText() {
return text; }
public void setText(String text) { this.text = text; } public int getRecordId() { return recordId; }}
class FormPrefs extends Form implements CommandListener{ private Command cmBack, cmSave; private TodoMIDlet midlet; private ChoiceGroup cgPrefs;
public FormPrefs(String title, TodoMIDlet midlet, boolean flags[])
{ // Call the Form constructor super(title);
this.midlet = midlet; cmSave = new Command("Save", Command.SCREEN, 1); cmBack = new Command("Back", Command.BACK, 2);
cgPrefs = new ChoiceGroup("Preferences", Choice.MULTIPLE); cgPrefs.append("Sort by Priority", null); cgPrefs.append("Show Priority", null);
cgPrefs.setSelectedFlags(flags);
append(cgPrefs); addCommand(cmBack); addCommand(cmSave);
setCommandListener(this); }
public void commandAction(Command c, Displayable s) { if (c == cmSave) { midlet.savePreferences(cgPrefs.isSelected(0), cgPrefs.isSelected(1)); }
midlet.displayMgr.popDisplayable(); }}
Gmail:-
MailMIDlet.java Coding:-
import javax.microedition.midlet.*;import javax.microedition.lcdui.*;
public class MailMIDlet extends MIDlet { public static MailMIDlet instance; private MailScreens displayable = new MailScreens();
public static Image appIcon = null; public static Image sendMessageIcon = null;
/** Constructor */ public MailMIDlet() { instance = this; try{ System.out.println("Trying to load png file"); appIcon = Image.createImage("/MailApplication.png"); sendMessageIcon = Image.createImage("/PushPuzzle.png"); }catch(Exception e){ System.out.println("value of send message png is "+sendMessageIcon); }
}
/** Main method */ public void startApp() { Display.getDisplay(this).setCurrent(displayable); }
/** Handle pausing the MIDlet */ public void pauseApp() { }
/** Handle destroying the MIDlet */ public void destroyApp(boolean unconditional) { }
/** Quit the MIDlet */ public static void quitApp() { instance.destroyApp(true); instance.notifyDestroyed(); instance = null; }
}
MailScreen.java:-import java.util.Hashtable;import java.util.Vector;import java.util.Enumeration;import java.io.*;
import javax.microedition.lcdui.*;import javax.microedition.lcdui.TextField;import javax.microedition.lcdui.ChoiceGroup;import javax.microedition.lcdui.Form;import javax.microedition.lcdui.List;import javax.microedition.lcdui.Alert;import javax.microedition.lcdui.TextBox;import javax.microedition.lcdui.StringItem;import javax.microedition.rms.*;import javax.microedition.io.*;
import javax.microedition.lcdui.Command;import javax.microedition.lcdui.CommandListener;
public class MailScreens extends List implements CommandListener { public TextField loginname,password; public ChoiceGroup cb = null; private List OutBoxScreen,InBoxScreen; private Form SettingScreen,SendMessageForm,settings; private TextBox ReadMailScreen = null; TextField toField = null; TextField subjectField = null; TextField contentField = null; int CurrentScreen =0; //DataStore Object. private DataManager datamanager = null; public Command CMDShowQ,CMDEXIT,CMDSendMail,CMDNext,backToInbox,backToMain,backToSettings,help; private TextField login_txt, password_txt,newAccount; private Image appIcon, sendMessageIcon; private Hashtable sentht = null; private Hashtable inboxht = null; private Hashtable outboxht = null;
String login_save = null; //Commands...... public static final int UPDATE_SETTINGS = 1; public static final int ENTER_SETTINGS = 2; private static final int INBOX = 0; private static final int OUTBOX = 3; private static final int BACK = 4; //DataBase; RecordStore rs = null; String rs_saved = "0"; // default not saved String rs_id = ""; String rs_pass = ""; //General usage Variables.. public int opr = 0; int i = 0; private Vector list = null; /** Constructor */ public MailScreens() { super("E-Mail",List.IMPLICIT); try{ this.append("Send Mail",Image.createImage("/MailApplication.png"));
this.append("Inbox",Image.createImage("/MailApplication.png")); this.append("Outbox",Image.createImage("/MailApplication.png")); this.append("Mail Settings",Image.createImage("/MailApplication.png")); }catch(Exception e){
} this.setCommandListener(this); CMDShowQ = new Command("Ok",1,Command.OK); CMDEXIT = new Command("Exit",2,Command.EXIT); this.addCommand(CMDShowQ); this.addCommand(CMDEXIT); this.setCommandListener(this); //SettingUp DataManager Object. datamanager = DataManager.getDataManager(); }
private void showAlert(String alert){ Alert alt = new Alert("alert");
alt.setString(alert); alt.setTimeout(1000); Display.getDisplay(MailMIDlet.instance).setCurrent(alt); } private void showWaitScreen(){ Form waitForm = new Form("Wait Form"); waitForm.append("Please Wait..."); Display.getDisplay(MailMIDlet.instance).setCurrent(waitForm); }
private void showOutboxScreen(){ OutBoxScreen = new List("OutBox",List.IMPLICIT); try{ outboxht = datamanager.getOutBox(); Enumeration enu = outboxht.keys(); while(enu.hasMoreElements()){ String key =(String)enu.nextElement(); Vector keyValue = (Vector)outboxht.get(key); String subject =(String) keyValue.elementAt(1); OutBoxScreen.append(subject,MailMIDlet.sendMessageIcon); } CurrentScreen = 2; CMDNext = new Command("Show Mail",1,Command.OK); OutBoxScreen.setCommandListener(this); Display.getDisplay(MailMIDlet.instance).setCurrent(OutBoxScreen); }catch(Exception e){ System.out.println("Exception is "+e.getMessage()); } CMDNext = new Command("ShowMail",1,Command.OK); backToMain = new Command("BackToEmail",2,Command.BACK); OutBoxScreen.addCommand(CMDNext); OutBoxScreen.addCommand(backToMain); OutBoxScreen.setCommandListener(this); Display.getDisplay(MailMIDlet.instance).setCurrent(OutBoxScreen); }
private void showInboxScreen(){ try{ InBoxScreen = new List("InBox",List.IMPLICIT); inboxht = datamanager.getInBox();
Enumeration enu = inboxht.keys(); while(enu.hasMoreElements()){ String key =(String)enu.nextElement(); Vector keyValue = (Vector)inboxht.get(key); String subject =(String) keyValue.elementAt(1); InBoxScreen.append(subject,MailMIDlet.sendMessageIcon); } CurrentScreen =1; CMDNext = new Command("Show Mail",1,Command.OK); backToMain = new Command("BackToEmail",2,Command.BACK); InBoxScreen.addCommand(CMDNext); InBoxScreen.addCommand(backToMain); InBoxScreen.setCommandListener(this); Display.getDisplay(MailMIDlet.instance).setCurrent(InBoxScreen); }catch(Exception e){
System.out.println("Exception is "+e.getMessage()); } } private void showMailScreen(Hashtable inboxht,String key){ TextBox mailBox = new TextBox("Read Mail","",200,TextField.ANY); Vector mailItem = (Vector)inboxht.get(key.trim()); String fromID = (String)mailItem.elementAt(0); String mailContent = (String)mailItem.elementAt(2); mailBox.setString("Mail From : - "+fromID+" \n**************\n"+mailContent);
backToInbox = new Command("Back",1,Command.BACK); mailBox.addCommand(backToInbox/*Back to mail inbox Command.*/); mailBox.setCommandListener(this); Display.getDisplay(MailMIDlet.instance).setCurrent(mailBox); }
private void showSendMessageScreen(){ try{ SendMessageForm = new Form("SendMessageForm"); toField = new TextField("To: ","",50,TextField.ANY); subjectField = new TextField("Subject: ","",50,TextField.ANY); contentField = new TextField("Content: ","",50,TextField.ANY);
SendMessageForm.append(toField); SendMessageForm.append(subjectField); SendMessageForm.append(contentField); backToMain = new Command("BackToEmail",2,Command.BACK); CMDSendMail = new Command("Send",1,Command.OK); SendMessageForm.addCommand(backToMain); SendMessageForm.addCommand(CMDSendMail); SendMessageForm.setCommandListener(this); Display.getDisplay(MailMIDlet.instance).setCurrent(SendMessageForm); }catch(Exception e){ System.out.println("Exception is "+e.getMessage()); } } private void settingsScreen(){ settings = new Form("Settings"); newAccount = new TextField("Set_New_Mail","",25,TextField.ANY); settings.append(newAccount); backToMain = new Command("BackToEmail",2,Command.BACK); backToSettings = new Command("setValue",1,Command.BACK); settings.setCommandListener(this); settings.addCommand(backToMain); settings.addCommand(backToSettings); Display.getDisplay(MailMIDlet.instance).setCurrent(settings); }
/**Handle command events*/ public void commandAction(Command c, Displayable disp) { int cmdType = c.getCommandType(); /** @todo Add command handling code */ if (cmdType == Command.EXIT) { MailMIDlet.quitApp(); } if(c == backToInbox){ System.out.println("I want to go back to Invox sxreen"); if(CurrentScreen == 1){ showInboxScreen();
}else if(CurrentScreen == 2){ showOutboxScreen(); } } if(c == backToMain){ Display.getDisplay(MailMIDlet.instance).setCurrent(this); } if(c == backToSettings){ showAlert("Value is Set"); //settingsScreen(); newAccount.setString(""); } if(c == CMDSendMail){ showAlert("Your Message is Sent"); toField.setString(""); subjectField.setString(""); contentField.setString(""); } if(c == CMDShowQ){ int listIndex = this.getSelectedIndex(); switch(listIndex){ case 0:{ showSendMessageScreen(); break; } case 1: { showInboxScreen(); break; } case 2:{ showOutboxScreen(); break; } case 3:{ settingsScreen(); break; } } } if(c == CMDNext){
if(CurrentScreen == 1){ int keySelected = InBoxScreen.getSelectedIndex(); keySelected =keySelected+1; String valuekeySelected = ""+keySelected; showMailScreen(inboxht, valuekeySelected); }else if(CurrentScreen == 2){ int keySelected = OutBoxScreen.getSelectedIndex(); keySelected =keySelected+1; String valuekeySelected = ""+keySelected; showMailScreen(outboxht, valuekeySelected); } } }}
DataManager.java Coding:-
import java.util.Vector;import java.util.Hashtable;import java.util.Random;import java.util.Enumeration;import java.util.Timer;
public class DataManager { public static DataManager instance = null;
private Vector inbox = new Vector(10); private Hashtable htInbox = new Hashtable(10); private Vector outbox = new Vector(10); private Vector sentItems = new Vector(10); private Hashtable htOutbox = new Hashtable(10); private Hashtable htSentItem = new Hashtable(10); private Vector namesDB = null;
public DataManager(){ htInbox = new Hashtable(10); inbox = new Vector(10);
htOutbox = new Hashtable(10); outbox = new Vector(10); htSentItem = new Hashtable(10); sentItems = new Vector(10); namesDB = new Vector(100); } public static DataManager getDataManager(){ if (instance == null){ instance = new DataManager(); } return instance; } public Hashtable getInBox() { inbox.addElement("[email protected]"); inbox.addElement("Rick Calling"); inbox.addElement("Hello Rick how r u howz life"); htInbox.put("1",inbox); inbox = null; inbox = new Vector(10); inbox.addElement("[email protected]"); inbox.addElement("Romi died and his widow needs your help"); inbox.addElement("Hey u know romi died and his widow needs our help"); htInbox.put("2",inbox); inbox = null; inbox = new Vector(10); inbox.addElement("[email protected]"); inbox.addElement("Martina wants to meet. "); inbox.addElement("hey its' martina i wana meet you as early as possible"); htInbox.put("3",inbox); inbox = null; inbox = new Vector(10); inbox.addElement("[email protected]"); inbox.addElement("Its' TJ Hig."); inbox.addElement("hey man you havent' sent ny mail since long... Uhatz up."); htInbox.put("4",inbox); return htInbox; } public Hashtable getOutBox(){
outbox.addElement("[email protected]"); outbox.addElement("Romey hi how r u "); outbox.addElement("Hello Rick how r u howz life"); htOutbox.put("1",outbox); outbox = null; outbox = new Vector(10); outbox.addElement("[email protected]"); outbox.addElement("Hey u know Romi died"); outbox.addElement("Hey u know romi died and his widow needs our help"); htOutbox.put("2",outbox); outbox = null; outbox = new Vector(10); outbox.addElement("[email protected]"); outbox.addElement("hey TJ howz u doin."); outbox.addElement("hey man you havent' sent ny mail since long... Uhatz up."); htOutbox.put("3",outbox); outbox = null; outbox = new Vector(10); outbox.addElement("[email protected]"); outbox.addElement("Sarah i wana meet."); outbox.addElement("hey its' martina i wana meet you as early as possible"); htOutbox.put("4",outbox); return htOutbox; } public Hashtable getsentItems(){
sentItems.addElement("[email protected]"); sentItems.addElement("Rmick hi how r u "); sentItems.addElement("Hello Rmick how r u howz life"); htSentItem.put("1",sentItems); sentItems = null; sentItems = new Vector(10); sentItems.addElement("[email protected]"); sentItems.addElement("Hey u know Romi died"); sentItems.addElement("Hey u know romi died and his widow needs our help"); htSentItem.put("2",sentItems);
sentItems = null; sentItems = new Vector(10); sentItems.addElement("[email protected]"); sentItems.addElement("hey TJ howz u doin."); sentItems.addElement("hey man you havent' sent ny mail since long... Uhatz up."); htSentItem.put("3",sentItems); sentItems = null; sentItems = new Vector(10); sentItems.addElement("[email protected]"); sentItems.addElement("Sarah i wana meet."); sentItems.addElement("hey its' martina i wana meet you as early as possible"); htSentItem.put("4",sentItems); return htSentItem; }}
Time and Date:
TimeDate.java Coding:-
import java.util.Date;import javax.microedition.lcdui.Command;import javax.microedition.lcdui.CommandListener;import javax.microedition.lcdui.DateField;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Displayable;import javax.microedition.lcdui.Form;import javax.microedition.midlet.MIDlet;
public class TimeDate extends MIDlet implements CommandListener { private Display display;
private Form form = new Form("Today's Date");
private Date today = new Date(System.currentTimeMillis());
private Command exit = new Command("Exit", Command.EXIT, 1);
private DateField datefield = new DateField("bb", DateField.DATE_TIME);
public TimeDate() { display = Display.getDisplay(this); datefield.setDate(today); form.append(datefield); form.addCommand(exit); form.setCommandListener(this); }
public void startApp() { display.setCurrent(form); }
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(false); notifyDestroyed(); } }}
Video:-
VideoMIDlet.java Coding:-import java.io.*;
import javax.microedition.io.*;import javax.microedition.lcdui.*;import javax.microedition.midlet.*;import javax.microedition.media.*;import javax.microedition.media.control.*;
public class VideoMIDletextends MIDletimplements CommandListener, Runnable { private Display mDisplay; private Form mMainScreen; private Item mVideoItem; private VideoControl mVidc; private Command mPlayCommand; private Player mPlayer = null; public void startApp() { mDisplay = Display.getDisplay(this); if (mMainScreen == null) { mMainScreen = new Form("Video MIDlet"); mMainScreen.addCommand(new Command("Exit", Command.EXIT, 0)); mPlayCommand = new Command("Play", Command.SCREEN, 0); mMainScreen.addCommand(mPlayCommand); mMainScreen.setCommandListener(this); } mDisplay.setCurrent(mMainScreen); } public void pauseApp() {} public void destroyApp(boolean unconditional) { if (mPlayer != null) { mPlayer.close(); } }
public void commandAction(Command c, Displayable s) { if (c.getCommandType() == Command.EXIT) { destroyApp(true); notifyDestroyed(); } else { Form waitForm = new Form("Loading..."); mDisplay.setCurrent(waitForm); Thread t = new Thread(this); t.start(); } } public void run() { playFromResource(); } private void playFromResource() { try { InputStream in = getClass().getResourceAsStream("/fish.mpg"); mPlayer = Manager.createPlayer(in, "video/mpeg"); // player.start(); mPlayer.realize(); if ((mVidc = (VideoControl) mPlayer.getControl("VideoControl")) != null) { mVideoItem = (Item) mVidc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null); mMainScreen.append(mVideoItem); } mPlayer.start(); mMainScreen.removeCommand(mPlayCommand); mDisplay.setCurrent(mMainScreen); } catch (Exception e) { showException(e);
return; } } private void showException(Exception e) { Alert a = new Alert("Exception", e.toString(), null, null); a.setTimeout(Alert.FOREVER); mDisplay.setCurrent(a, mMainScreen); } }
BIBLIOGRAPHY
1. www.roseindia.net
2. www.java2s.com
3. Developing Mobile Applications Using Java (NIIT BOOK)