Primeiro, o que é o Mojax -> um projeto interessante (ainda em versão beta). Uma framework suite de pacotes) que permite ao programador desenvolver aplicações no estilo JME sem usar diretamente a mesma e sem ter conhecimento integral de JAVA. Basta conhecer JavaScript e XML/CSS
Com ajuda do Mojax você pode facilmente desenvolver uma aplicação J2ME com tabelas ou com funções de cliente do Google ou Yahoo Maps, Flickr, aplicativo de estoque, tudo isso com poucas linhas de código.
Exemplo de “Hello World”:
Ex. em mojax com uso de XML
<moblet default="main" name="HelloWorld">
<screen id="main">
<textbox>
HELLO WORLD!
</textbox>
</screen>
</moblet>
Ex. em Java
import javax.microedition.midlet.* ;
import javax.microedition.lcdui.*;
public class Hello extends MIDlet {
private Display display;
public Hello() {
display = Display.getDisplay(this);
}
public void startApp() {
Form f = new Form("main");
f.append("HELLO WORLD!");
display.setCurrent(f);
}
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
}
Ex. com uso de CSS
<moblet default="main">
<screen id="main" layout="vertical">
<box layout="vertical" style="border: 1px
solid #FF0000" valign="center"
halign="center">
<textbox style="border: 1px solid #00ff00">
HELLO
</textbox>
<textbox style="border: 1px solid #0000ff">
WORLD
</textbox>
</box>
</screen>
</moblet>
Ex. de um Menu com JavaScript
<screen id="main" layout="vertical"
valign="center" halign="center">
<textbox focusable="true"
onClick="show(info, 1)" width="100%">
Show info as Layer
</textbox>
<textbox focusable="true"
onClick="show(info)" width="100%">
Show info as Screen
</textbox>
</screen>
Exemplo em Mojax (Mobile Ajax) de uma aplicação LBS, uma alternativa para a dispositivos sem suporte a API Location (JSR 179) usando o Yahoo! Maps
import java.io.IOException;
import java.util.Hashtable;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import com.sun.me.web.path.Result;
import com.sun.me.web.path.ResultException;
import com.sun.me.web.request.Arg;
import com.sun.me.web.request.ProgressInputStream;
import com.sun.me.web.request.Request;
import com.sun.me.web.request.RequestListener;
import com.sun.me.web.request.Response;
import java.io.InputStream;
// Exemplo de MIDlet Mojax (Mobile Ajax) para pesquisa local com resultado exibido com o Yahoo! Maps
public class LocalSearchMidlet extends MIDlet implements CommandListener, RequestListener {
private static final boolean DEBUG = true;
// Recupera o APP ID para uso no Yahoo Maps API
private static final String APPID = "";
private static final int DEFAULT_RESULT_COUNT = 10;
private static final int MAX_MAP_ZOOM = 12;
private static final int DEFAULT_MAP_ZOOM = 6;
private static final int MIN_MAP_ZOOM = 1;
private Hashtable imageCache = new Hashtable(MAX_MAP_ZOOM - MIN_MAP_ZOOM);
private int mapZoomLevel = DEFAULT_MAP_ZOOM;
private Item selectedItem = null;
private static final String LOCAL_BASE = "http://local.yahooapis.com/LocalSearchService/V2/localSearch";
private static final String MAP_BASE = "http://api.local.yahoo.com/MapsService/V1/mapImage";
private String mapAllLink = null;
private static class Links {
String title;
String business;
String listing;
String map;
String tel;
String latitude;
String longitude;
};
private Links[] links = null;
private int start = 1;
private int totalResultsAvailable = start;
public LocalSearchMidlet() {
}
private Form queryForm; // MVDFields
private Command exitCommand;
private Form resultForm;
private Command searchCommand;
private Alert alert;
private TextField searchFor;
private TextField street;
private TextField location;
private Command mapCommand;
private Command listingCommand;
private Command businessCommand;
private ChoiceGroup sortGroup;
private Command mapAllCommand;
private Command backCommand;
private Command callCommand;
private Form mapForm;
private ImageItem mapImageItem;
private Command mapBackCommand;
private Command zoomInCommand;
private Command zoomOutCommand;
private Command selectCommand;
private Command nextCommand;
private Command prevCommand;
// MVDMethods
// Inicialização da interface da aplicação
private void initialize() {
getDisplay().setCurrent(get_queryForm());
}
public void commandAction(Command command, Displayable displayable) { // MVDCABegin
if (displayable == queryForm) { // MVDCABody
if (command == exitCommand) { //MVDCABody
exitMIDlet(); // MVDCAAction3
} else if (command == searchCommand) { // MVDCACase3
getDisplay().setCurrent(get_alert(), get_queryForm()); // MVDCAAction13
search();
} // MVDCACase13
}
else if (displayable == resultForm) {
if (command == exitCommand) {
exitMIDlet();// MVDCAAction16
}
else if (command == businessCommand) { // MVDCACase16
showBusiness();
// MVDCAAction38
}
else if (command == listingCommand) { // MVDCACase38
showListing();
// MVDCAAction36
}
else if (command == mapAllCommand) { // MVDCACase36
showAllOnMap();
// MVDCAAction48
}
else if (command == backCommand) { // MVDCACase48
getDisplay().setCurrent(get_queryForm()); // MVDCAAction50
}
else if (command == callCommand) { // MVDCACase50
call();
// MVDCAAction52
}
else if (command == mapCommand) { // MVDCACase52
getDisplay().setCurrent(get_alert(), get_resultForm()); // MVDCAAction89
map();
}
else if (command == prevCommand) { // MVDCACase89
start = Math.max(1, start - DEFAULT_RESULT_COUNT);
getDisplay().setCurrent(get_alert());
search();
// MVDCAAction98
}
else if (command == nextCommand) { // MVDCACase98
start = Math.min(totalResultsAvailable, start + DEFAULT_RESULT_COUNT);
getDisplay().setCurrent(get_alert());
search();
// MVDCAAction96
}
}
else if (displayable == mapForm) {
if (command == mapBackCommand) { // MVDCACase96
getDisplay().setCurrent(get_resultForm()); // MVDCAAction65
}
else if (command == exitCommand) {// MVDCACase65
exitMIDlet(); // MVDCAAction7
}
else if (command == zoomOutCommand) {// MVDCACase67
mapZoomLevel = Math.min(++mapZoomLevel, MAX_MAP_ZOOM);
switchZoomLevel(); // MVDCAAction94
}
else if (command == zoomInCommand) { // MVDCACase94
mapZoomLevel = Math.max(--mapZoomLevel, MIN_MAP_ZOOM);
switchZoomLevel();
}
}
}
public Display getDisplay() { // MVDGetDisplay
return Display.getDisplay(this);
}
public void exitMIDlet() { // MVDExitMidlet
getDisplay().setCurrent(null);
destroyApp(true);
notifyDestroyed();
}
public Form get_queryForm() {
if (queryForm == null) { // MVDGetBegin2
queryForm = new Form("Local Search", new Item[] { // MVDGetInit2
get_searchFor(),
get_location(),
get_street(),
get_sortGroup()
});
queryForm.addCommand(get_exitCommand());
queryForm.addCommand(get_searchCommand());
queryForm.setCommandListener(this);
}
return queryForm;
}
// MVDGetBegin5
public Command get_exitCommand() {
if (exitCommand == null) {
exitCommand = new Command("Exit", Command.EXIT, 1); // MVDGetInit5
}
}
public Form get_resultForm() {
if (resultForm == null) { // MVDGetBegin6
resultForm = new Form("Results", new Item[0]); // MVDGetInit6
resultForm.addCommand(get_mapCommand());
resultForm.addCommand(get_listingCommand());
resultForm.addCommand(get_businessCommand());
resultForm.addCommand(get_mapAllCommand());
resultForm.addCommand(get_callCommand());
resultForm.addCommand(get_backCommand());
resultForm.addCommand(get_exitCommand());
resultForm.addCommand(get_nextCommand());
resultForm.addCommand(get_prevCommand());
resultForm.setCommandListener(this);
}
return resultForm;
}
public Command get_searchCommand() {
if (searchCommand == null) { // MVDGetBegin12
searchCommand = new Command("Search", Command.OK, 1); // MVDGetInit12
}
return searchCommand;
}
public Alert get_alert() {
if (alert == null) { // MVDGetBegin14
alert = new Alert(null, "", null, AlertType.INFO); // MVDGetInit14
alert.setTimeout(-2);
}
return alert;
}
public TextField get_searchFor() {
if (searchFor == null) { // MVDGetBegin20
searchFor = new TextField("Search For:", "coffee", 120, TextField.ANY); // MVDGetInit20
}
return searchFor;
}
public TextField get_street() {
if (street == null) { // MVDGetBegin21
street = new TextField("Street:", null, 120, TextField.ANY); // MVDGetInit21
}
return street;
}
public TextField get_location() {
if (location == null) { // MVDGetBegin24
location = new TextField("Location:", "95054", 120, TextField.ANY);//GEN-LINE:MVDGetInit24
}
return location;
}
public Command get_mapCommand() {
if (mapCommand == null) { // MVDGetBegin33
mapCommand = new Command("Map", Command.OK, 1);//GEN-LINE:MVDGetInit33
}
return mapCommand;
}
public Command get_listingCommand() { //GEN-BEGIN:MVDGetBegin35
if (listingCommand == null) {
listingCommand = new Command("Listing", Command.ITEM, 1); // MVDGetInit35
}
return listingCommand;
}
//GEN-BEGIN:MVDGetBegin37
public Command get_businessCommand() {
if (businessCommand == null) {
businessCommand = new Command("Business", Command.ITEM, 1); // MVDGetInit37
}
return businessCommand;
}
// MVDGetBegin39
public ChoiceGroup get_sortGroup() {
if (sortGroup == null) {
sortGroup = new ChoiceGroup("Sort Results By:", Choice.POPUP, new String[] { // MVDGetInit39
"Distance",
"Title",
"Rating",
"Relevance"
}, new Image[] {
null,
null,
null,
null
});
sortGroup.setSelectedFlags(new boolean[] {
true,
false,
false,
false
});
}
return sortGroup;
}
// MVDGetBegin47
public Command get_mapAllCommand() {
if (mapAllCommand == null) {
mapAllCommand = new Command("Map All", Command.ITEM, 1); // MVDGetInit47
}
return mapAllCommand;
}
// MVDGetBegin49
public Command get_backCommand() {
if (backCommand == null) {
backCommand = new Command("Back", Command.BACK, 1); // MVDGetInit49
}
return backCommand;
}
// MVDGetBegin51
public Command get_callCommand() {
if (callCommand == null) {
callCommand = new Command("Call", Command.ITEM, 1); // MVDGetInit51
}
return callCommand;
}
// MVDGetBegin53
public Form get_mapForm() {
if (mapForm == null) {
mapForm = new Form("Map", new Item[] {get_mapImageItem()}); // MVDGetInit53
mapForm.addCommand(get_zoomInCommand());
mapForm.addCommand(get_zoomOutCommand());
mapForm.addCommand(get_mapBackCommand());
mapForm.addCommand(get_exitCommand());
mapForm.setCommandListener(this);
}
return mapForm;
}
// MVDGetBegin54
public ImageItem get_mapImageItem() {
if (mapImageItem == null) {
mapImageItem = new ImageItem("", null, ImageItem.LAYOUT_DEFAULT, null); // MVDGetInit54
mapImageItem.setLayout(Item.LAYOUT_CENTER | Item.LAYOUT_VCENTER);
}
return mapImageItem;
}
// MVDGetBegin55
public Command get_mapBackCommand() {
if (mapBackCommand == null) {
mapBackCommand = new Command("Back", Command.BACK, 1); // MVDGetInit55
}
return mapBackCommand;
}
// método para aumentaro zoom
// MVDGetBegin58
public Command get_zoomInCommand() {
if (zoomInCommand == null) {
zoomInCommand = new Command("Zoom In", Command.ITEM, 1); // MVDGetInit58
}
return zoomInCommand;
}
// MVDGetBegin60
public Command get_zoomOutCommand() {
if (zoomOutCommand == null) { // MVDGetBegin60
zoomOutCommand = new Command("Zoom Out", Command.ITEM, 1);//GEN-LINE:MVDGetInit60
}
return zoomOutCommand;
}
// MVDGetBegin90
public Command get_selectCommand() {
if (selectCommand == null) {
selectCommand = new Command("Select", Command.OK, 1); // MVDGetInit90
}
return selectCommand;
}
// MVDGetBegin95
public Command get_nextCommand() {
if (nextCommand == null) {
nextCommand = new Command("Next", Command.ITEM, 1); // MVDGetInit95
}
return nextCommand;
}
// método que executa o comando/tela anterior diretamente
// MVDGetBegin97
public Command get_prevCommand() {
if (prevCommand == null) {
prevCommand = new Command("Previous", Command.ITEM, 1);//GEN-LINE:MVDGetInit97
}
return prevCommand;
}
private void switchZoomLevel() {
final Image img = (Image) imageCache.get(new Integer(mapZoomLevel));
if (img == null) {
getDisplay().setCurrent(get_alert());
map();
} else {
get_mapImageItem().setImage(img);
getDisplay().setCurrent(get_mapForm());
}
}
public void startApp() {
initialize();
}
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
private void errorAlert(final String message, final Exception ex, final Displayable next) {
final Alert alert = get_alert();
final String exMsg = ex == null ? null : ex.getMessage();
final String text = exMsg == null ? message : message + ": " + exMsg;
alert.setString(text);
alert.setTimeout(Math.max(3000, alert.getDefaultTimeout()));
if (DEBUG)
System.err.println("ERROR: " + text);
getDisplay().setCurrent(alert, next);
}
private Links getSelectedLink() {
if (selectedItem == null || links == null) {
errorAlert("No item selected!", null, get_resultForm());
return null;
}
final String label = selectedItem.getLabel();
if (label == null) {
errorAlert("No item selected!", null, get_resultForm());
return null;
}
for (int i=0; i < links.length; i++) {
if (label.equals(links[i].title))
return links[i];
}
return null;
}
private void map() {
final Links link = getSelectedLink();
if (link == null) {
return;
}
final Arg[] args = {
new Arg("output", "json"),
new Arg("appid", APPID),
new Arg("latitude", link.latitude),
new Arg("longitude", link.longitude),
new Arg("image_height", Integer.toString(get_mapForm().getHeight())),
new Arg("image_width", Integer.toString(get_mapForm().getWidth())),
new Arg("zoom", Integer.toString(mapZoomLevel))
};
get_alert().setString("Getting map image location...");
Request.get(MAP_BASE, args, null, this, get_mapForm());
}
private void mapResponse(final Response response) {
final Exception ex = response.getException();
if (ex != null || response.getCode() != HttpConnection.HTTP_OK) {
errorAlert("Error connecting to map service", ex, get_resultForm());
return;
}
final Result result = response.getResult();
final String location;
try {
location = result.getAsString("ResultSet.Result");
}
catch (ResultException rex) {
errorAlert("Error extracting map location", rex, get_resultForm());
return;
}
get_alert().setString("Getting map image...");
final int imgResponseCode;
final HttpConnection imgConn;
try {
imgConn = (HttpConnection) Connector.open(location);
imgConn.setRequestProperty("Accept", "image/png");
imgResponseCode = imgConn.getResponseCode();
}
catch (IOException iex) {
errorAlert("Error downloading map image", iex, get_resultForm());
return;
}
if (imgResponseCode != HttpConnection.HTTP_OK) {
errorAlert("HTTP error downloading map image: " + imgResponseCode, null, get_resultForm());
return;
}
final Image mapImage;
try {
final int totalToReceive = imgConn.getHeaderFieldInt(Arg.CONTENT_LENGTH, 0);
final InputStream is =
new ProgressInputStream(imgConn.openInputStream(), totalToReceive, this, null, 512);
mapImage = Image.createImage(is);
}
catch (IOException iex) {
errorAlert("Failed to create map image", iex, get_resultForm());
return;
}
finally {
try { imgConn.close(); } catch (IOException ignore) {}
}
imageCache.put(new Integer(mapZoomLevel), mapImage);
get_mapImageItem().setImage(mapImage);
getDisplay().setCurrent(get_mapForm());
}
private void showAllOnMap() {
launch(mapAllLink);
}
private void showListing() {
final Links link = getSelectedLink();
if (link == null)
return;
launch(link.listing);
}
private void showBusiness() {
final Links link = getSelectedLink();
if (link == null)
return;
launch(link.business);
}
private void call() {
final Links link = getSelectedLink();
if (link == null)
return;
launch("tel:" + stripPhoneNumber(link.tel));
}
private void launch(final String url) {
final boolean exitNeeded;
try {
if (DEBUG) {
System.out.println("Launching Platform Request for: " + url);
}
exitNeeded = platformRequest(url);
if (exitNeeded) {
errorAlert("Please exit the MIDlet to access the page or to make the call", null, resultForm);
}
} catch (ConnectionNotFoundException cx) {
errorAlert(url.substring(0, url.indexOf(':')) + " connection not found for platformRequest", cx, resultForm);
}
}
private void search() {
final Arg[] args = {
new Arg("output", "json"),
new Arg("appid", APPID),
new Arg("query", searchFor.getString()),
new Arg("location", location.getString()),
new Arg("sort", sortGroup.getString(sortGroup.getSelectedIndex()).toLowerCase()),
new Arg("start", Integer.toString(start)),
null
};
final String str = street.getString();
if (!"".equals(str)) {
args[6] = new Arg("street", str);
}
get_alert().setString("Searching...");
Request.get(LOCAL_BASE, args, null, this, get_resultForm());
}
private void searchResponse(final Response response) {
final Exception ex = response.getException();
if (ex != null || response.getCode() != HttpConnection.HTTP_OK) {
errorAlert("Error connecting to search service", ex, get_resultForm());
return;
}
final Result result = response.getResult();
try {
mapAllLink = result.getAsString("ResultSet.ResultSetMapUrl");
totalResultsAvailable = result.getAsInteger("ResultSet.totalResultsAvailable");
final int resultCount = result.getSizeOfArray("ResultSet.Result");
links = new Links[resultCount];
get_resultForm().deleteAll();
for (int i=0; i < resultCount; i++) {
final String title = result.getAsString("ResultSet.Result["+i+"].Title");
final String address = result.getAsString("ResultSet.Result["+i+"].Address");
final String phone = result.getAsString("ResultSet.Result["+i+"].Phone");
final String distance = result.getAsString("ResultSet.Result["+i+"].Distance");
links[i] = new Links();
links[i].title = title;
links[i].map = result.getAsString("ResultSet.Result["+i+"].MapUrl");
links[i].listing = result.getAsString("ResultSet.Result["+i+"].ClickUrl");
links[i].business = result.getAsString("ResultSet.Result["+i+"].BusinessClickUrl");
links[i].tel = result.getAsString("ResultSet.Result["+i+"].Phone");
links[i].latitude = result.getAsString("ResultSet.Result["+i+"].Latitude");
links[i].longitude = result.getAsString("ResultSet.Result["+i+"].Longitude");
final String avgRating = result.getAsString("ResultSet.Result["+i+"].Rating.AverageRating");
final String displayString =
address + "\n" +
distance + " miles" +
("".equals(avgRating) ? "" : ", " + avgRating + "*") + "\n" +
phone;
final StringItem stringItem = new StringItem(title, displayString, StringItem.PLAIN);
stringItem.setLayout(Item.LAYOUT_NEWLINE_BEFORE | Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_LEFT);
stringItem.setDefaultCommand(get_selectCommand());
stringItem.setItemCommandListener(new ItemCommandListener() {
public void commandAction(Command command, Item item) {
if (selectedItem != item) {
selectedItem = item;
imageCache.clear();
}
}
});
get_resultForm().append(stringItem);
}
} catch (ResultException rex) {
errorAlert("Error extracting result information", rex, get_resultForm());
return;
}
getDisplay().setCurrent(get_resultForm());
}
private String stripPhoneNumber(final String str) {
final char[] buf = new char[str.length()];
str.getChars(0, buf.length, buf, 0);
final StringBuffer sbuf = new StringBuffer(buf.length);
for (int i=0; i < buf.length; i++) {
if (buf[i] == '(') { }
else if (buf[i] == ')') { }
else if (buf[i] == '-') { }
else {
sbuf.append(buf[i]);
}
}
return sbuf.toString();
}
public void readProgress(final Object context, final int bytes, final int total) {
get_alert().setString("Read " + bytes + (total > 0 ? "/" + total : ""));
}
public void writeProgress(final Object context, final int bytes, final int total) {
get_alert().setString("Wrote " + bytes + (total > 0 ? "/" + total : ""));
}
public void done(final Object context, final Response response) throws Exception {
get_alert().setString(null);
if (context == mapForm) {
mapResponse(response);
}
else if (context == resultForm) {
searchResponse(response);
}
else {
throw new IllegalArgumentException("unknown context returned: " + context.toString());
}
}
}
Mais info sobre o exemplo: https://meapplicationdevelopers.dev.java.net/source/browse/meapplicationdevelopers/demobox/mobileajax/samples/midp/local/?rev=284
Site oficial do Mojax -> http://mojax.mfoundry.com/display/mojax/Main+Page