Monday, June 21, 2010

XML Parsing in J2ME

XML Parsing in J2ME

i have worked with this below example its working try it.....

Here is an example for XML parsing in J2ME.
In this example, username and password will be passed to the server
using http connection and application receives login status.
login status will be displayed in an Alert.

Before you start your coding you have to add kxml package in your application.
1. download the kxml zip file - http://kxml.objectweb.org/software/downloads/
2. Right click your project name in the netbeans and select properies
3. select build-> libraries and resources and add the downloaded zip file.
-----------------------------
<>
<>
<> login success


------------------------------

package ParseExample;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import ParseExample.RSSParser.RSSListener;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

/**
* @author test
*/
public class XmlParseSample extends MIDlet implements ItemCommandListener, RSSListener {
private Display display;
private TextField username, password;
private StringItem login;
private Command select;
private Form loginForm;
private String loginStatus;
public XmlParseSample() {
display = Display.getDisplay(this);
loginForm = new Form("Login");
username = new TextField("Username", "", 12, TextField.ANY);
password = new TextField("Password", "", 8, TextField.PASSWORD);
// Using StringItem as Button
login = new StringItem("", "Login", StringItem.BUTTON);
select = new Command("Select", Command.OK, 0);
}

public void startApp() {
loginForm.append(username);
loginForm.append(password);
loginForm.append(login);
login.setDefaultCommand(select);
login.setItemCommandListener(this);
display.setCurrent(loginForm);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command cmd, Item item) {
if (cmd == select && item == login) {
String user = username.getString();
String pass = password.getString();
String url = "http://..........?username=" + user + "&password=" + pass;
try{
RSSParser parser = new RSSParser();
parser.setRSSListener(this);
}
catch (Exception e) {
}
}
}

public void itemParsed(String message) {
this.loginStatus = message;
Alert a = new Alert("Exception", loginStatus,
null, null);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}

public void exception(java.io.IOException ioe) {
Alert a = new Alert("Exception", ioe.toString(),
null, null);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
}

-----------------------------

package ParseExample;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import javax.microedition.io.*;

import org.kxml.*;
import org.kxml.parser.*;

public class RSSParser {
XmlParseSample xmlParseSample;
protected RSSListener mRSSListener;
public void setRSSListener(RSSListener listener){
mRSSListener = listener;
}
//non blocking
public void parse(final String url) {
Thread t = new Thread() {
public void run() {
HttpConnection hc = null;
try {
hc = (HttpConnection) Connector.open(url);
parse(hc.openInputStream());
}
catch (IOException ioe) {
mRSSListener.exception(ioe);
}
finally {
try {
if (hc != null) {
hc.close();
}
}
catch (IOException ignored) {
}
}
}
};
t.start();
}
// Blocking.
public void parse(InputStream in) throws IOException {
Reader reader = new InputStreamReader(in);
XmlParser parser = new XmlParser(reader);
ParseEvent pe = null;
parser.read(Xml.START_TAG, null, "login");
boolean trucking = true;
while (trucking) {
pe = parser.read();
if (pe.getType() == Xml.START_TAG) {
String name = pe.getName();
if (name.equals("status")) {
while ((pe.getType() != Xml.END_TAG) ||
(pe.getName().equals(name) == false)) {
pe = parser.read();
if (pe.getType() == Xml.START_TAG &&
pe.getName().equals("message")) {
pe = parser.read();
message = pe.getText();
}
}
mRSSListener.itemParsed(message);
}
else{
while ((pe.getType() != Xml.END_TAG) ||
(pe.getName().equals(name) == false)) {
pe = parser.read();
}
}
}
if (pe.getType() == Xml.END_TAG &&
pe.getName().equals("login")) {
trucking = false;
}
}
}

public interface RSSListener {
public void itemParsed(String message);
public void exception(java.io.IOException ioe);
}
}

Sunday, April 18, 2010

Dynamic Columns In Ext JS Grid

Dynamic Columns In Ext JS Grid

i hope this will be helpful to develop a Ext js Grid with dynamic columns
here i have attached my js file and json format

My JavaScript file

Ext.onReady(function(){
var proxy= new Ext.data.HttpProxy(
{url: 'sample1.jsp'}

);
var reader=new Ext.data.JsonReader(
{

root:'root'

});

var store= new Ext.data.Store({
proxy:proxy,
reader: reader,
remoteSort: true
});
store.load();


//===================================

Ext.data.DynamicJsonReader = function(config){

Ext.data.DynamicJsonReader.superclass.constructor.call(this, config, []);

};

Ext.extend(Ext.data.DynamicJsonReader, Ext.data.JsonReader, {

readRecords : function(o){
alert("hi");

this.jsonData = o;
if(o.metaData){
delete this.ef;
this.meta = o.metaData;
this.recordType = Ext.data.Record.create(o.metaData.fields);
this.onMetaChange(this.meta, this.recordType, o);


} else {
var data = this.meta.root ? this.getJsonAccessor(this.meta.root)(o) : o;
if (Ext.isArray(data) && data[0]) {
delete this.ef;
var fields = [];
for (var fieldName in data[0]) {
fields.push(fieldName);
}
this.meta.fields = fields;
this.recordType = Ext.data.Record.create(fields);
this.onMetaChange(this.meta, this.recordType, o);
}
}

var s = this.meta, Record = this.recordType,
f = Record.prototype.fields, fi = f.items, fl = f.length;
if (!this.ef) {
if(s.totalProperty) {
this.getTotal = this.getJsonAccessor(s.totalProperty);
}
if(s.successProperty) {
this.getSuccess = this.getJsonAccessor(s.successProperty);
}
this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
if (s.id) {
var g = this.getJsonAccessor(s.id);
this.getId = function(rec) {
var r = g(rec);
return (r === undefined || r === "") ? null : r;
};
} else {
this.getId = function(){return null;};
}
this.ef = [];
for(var i = 0; i < fl; i++){
f = fi[i];
var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
this.ef[i] = this.getJsonAccessor(map);
}
}
var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
if(s.totalProperty){
var v = parseInt(this.getTotal(o), 10);
if(!isNaN(v)){
totalRecords = v;
}
}
if(s.successProperty){
var v = this.getSuccess(o);
if(v === false || v === 'false'){
success = false;
}
}
var records = [];
for(var i = 0; i < c; i++){
var n = root[i];
var values = {};
var id = this.getId(n);
for(var j = 0; j < fl; j++){
f = fi[j];
var v = this.ef[j](n);
values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, n);
}
var record = new Record(values, id);
record.json = n;

records[i] = record;
}

return {

success : success,
records : records,
totalRecords : totalRecords

};
}
});
Ext.grid.DynamicColumnModel = function(store, config){

Ext.grid.DynamicColumnModel.superclass.constructor.call(this, Ext.apply({store: store, columns: []}, config));
if (store.fields) {

this.reconfigure();

}

store.on('load', this.reconfigure, this);
};
Ext.extend(Ext.grid.DynamicColumnModel, Ext.grid.ColumnModel, {
reconfigure: function(){
var cols = [];
this.store.fields.each(function(field){
cols.push({header: field.name, dataIndex: field.name});
});
this.setConfig(cols);
}
});
var grid=new Ext.grid.GridPanel({
//title: 'test',
//id: 'test',
width: 1000,
height: 200,
cm: new Ext.grid.DynamicColumnModel(store),
selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
store: store,
//enableColLock: true,
//renderTo: Ext.getBody(),
viewConfig :{
forceFit:true
}
});
grid.render(document.body);
});




my json output format from the server

{ metaData:{ "totalProperty":"total", "root":"root", "id":"id", "fields":[ { "name":"statusid", "type":"int" } { "name":"statusname", "type":"string" } { "name":"statusdesc", "type":"string" } ] }, "success":"true", "totals":3, "records":[ {"statusid":"1","statusname":"New","statusdesc":"new description"},{"statusid":"2","statusname":"Open","statusdesc":"Open description"},{"statusid":"3","statusname":"Closed","statusdesc":"Closed description"}],columns:[ { "header":"STATUSID", "dataIndex":"statusid" } , { "header":"STATUSNAME", "dataIndex":"statusname" } , { "header":"STATUSDESC", "dataIndex":"statusdesc" } ] }