Sunday 11 November 2012

Displaying Background Image on BlackBerry Screen

To Display a Background Image on BlackBerry Screen,you need to use the below Code:

Package Structure:




Step-1: Create a BlackBerry Project with the name BackgroundImage
Step-2: Create a Main Class with the name BackGroundApp
Step-3: Create a Class with the name BackGroundScreen
Step-4: Copy and paste your Background Image under your project res/img folder.

BackGroundApp:
import net.rim.device.api.ui.UiApplication;
public class BackGroundApp extends UiApplication {
private static BackGroundApp app;
private BackGroundScreen screen;
public BackGroundApp() {
screen = new BackGroundScreen();
pushScreen(screen);
}
public static void main(String args[]) {
app = new BackGroundApp();
app.enterEventDispatcher();
}
    }

BackGroundScreen:
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class BackGroundScreen extends MainScreen {
private VerticalFieldManager mainManager;
private VerticalFieldManager subManager;
public BackGroundScreen(){
final Bitmap backgroundBitmap = Bitmap.getBitmapResource("background.png");
mainManager = new VerticalFieldManager(
net.rim.device.api.ui.container.VerticalFieldManager.NO_VERTICAL_SCROLLBAR
| net.rim.device.api.ui.container.VerticalFieldManager.NO_VERTICAL_SCROLLBAR) {
public void paint(Graphics graphics) {
graphics.drawBitmap(0, 0, Display.getWidth(),
Display.getHeight(), backgroundBitmap, 0, 0);
super.paint(graphics);
}
};
subManager = new VerticalFieldManager(
net.rim.device.api.ui.container.VerticalFieldManager.VERTICAL_SCROLL
| net.rim.device.api.ui.container.VerticalFieldManager.VERTICAL_SCROLLBAR) {
protected void sublayout(int maxWidth, int maxHeight) {
int displayWidth = Display.getWidth();
int displayHeight = Display.getHeight();
super.sublayout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
};
add(mainManager);
mainManager.add(subManager);
        }
               }
Output:








Saturday 10 November 2012

How to Place ads on Blackberry Application

If you have any requirement to place adverstisements like Banner Ads,Text adds etc...on to your Blackberry Application.Have a look at Below Code:

If you want to know more Information regarding Placing adds.Please have a look at BlackBerry Documents Click Here

Package Structure:


Step-1:Create a Project with any Name(Here I have Created with the name AddsonBlackBerry)
Step-2:Create a Class with the name AdDemo
Step-3: Place your Add Image under res/img Folder.

Finally Code Your AdDemo Class:

import java.util.Hashtable;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.UiApplication;
import net.rimlib.blackberry.api.advertising.app.Banner;
public class AdDemo extends UiApplication {
public static void main(String[] args) {
AdDemo theApp = new AdDemo();
theApp.enterEventDispatcher();
}
public AdDemo() {
pushScreen(new AdDemoScreen());
}
   }
 class AdDemoScreen extends MainScreen {
final Banner bannerAd;
public AdDemoScreen() {
Bitmap bit = Bitmap.getBitmapResource("BannerAd.png");
bannerAd = new Banner(85983, null,60000 , bit); bannerAd.setMMASize(Banner.MMA_SIZE_EXTRA_EXTRA_LARGE);
VerticalFieldManager vfm = new VerticalFieldManager( Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR
| Field.USE_ALL_WIDTH);
HorizontalFieldManager hfm = new HorizontalFieldManager(
Field.FIELD_HCENTER | Field.FIELD_VCENTER);
hfm.add(bannerAd);
vfm.add(hfm);
add(vfm);
bannerAd.setFocus();
} 
protected boolean navigationClick(int status, int time) {
if (bannerAd.isFocus()) {
Dialog.alert("Hellloooo");
}
return true;
}
}
Note: If you click on your Banner add and you want to perform some action,you can place the below logic:
protected boolean navigationClick(int status, int time) {
if (bannerAd.isFocus()) {
Dialog.alert("Hellloooo");
}
return true;
}

OutPut:





Thursday 8 November 2012

LWUIT Theme in J2me Application(Nokia)

If  you want to apply Themes to Your Nokia Application ,You can use the below Code:

1)Create a Project with the Name LWUITTheme
2)Create a Midlet class
3)Copy the LWUITtheme.res file to your "res" folder(Download  LWUITtheme.res  form Click Here )
Note: To Successfully Execute this Application you require LWUIT Jar file(You can get this jar file from Click Here )

PackageStructure:

ThemeMidlet :
import com.sun.lwuit.Display;import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import javax.microedition.midlet.MIDlet;
public class ThemeMidlet extends MIDlet {
    private Form form;
    private List list;
    private Object[] items;
    public ThemeMidlet() {
        Display.init(this);
        items = new Object[]{"Item1", "Item2", "Item3", "Item3", "Item4", "Item5"};
        list = new List(items);
        form = new Form("LWUIT Theme");
        //for the list to cover the entire screen width we need to set it    
        //list.setPreferredW(form.getWidth());
    }
   public void startApp() {
        try {
            Resources res = Resources.open("/res/LWUITtheme.res");
            UIManager.getInstance().setThemeProps(res.getTheme("LWUITDefault"));
            form.addComponent(list);
            form.show();
        } catch (Exception e) {
        }
    }
    public void pauseApp() {
    }
    public void destroyApp(boolean unconditional) {
    }
   }
OutPut:





Wednesday 7 November 2012

RssFeed Reader in J2me(LWUIT)

This article Contains the Code to read an RssFile in j2me.After execution ,You can able to display the Title and an Image on Nokia Screen

The Midlet Class:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.sun.lwuit.*;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import java.util.Vector;
import javax.microedition.midlet.*;
/**
 * @author pavan
 */
public class RssMidlet extends MIDlet implements ActionListener {
    private List rssFeedList;
    private Vector rssFeed;
    private Image image;
    private Form form1;
    private Command cmdExit, cmdDetails;
//Constructor 
      public RssMidlet() {
        Display.init(this);
        rssFeed = new Vector();
        cmdExit = new Command("Exit");
        cmdDetails = new Command("Details");
        form1 = new Form();
        form1.addCommand(cmdDetails);
        form1.addCommand(cmdExit);
        form1.setFocus(true);
        form1.addCommandListener(this);
        form1.setScrollableY(true);
        form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
        rssFeedList = new List(rssFeed);
        rssFeedList.setRenderer(new NewsListCellRenderer());
        rssFeedList.setFixedSelection(List.FIXED_NONE);
        rssFeedList.setItemGap(0);
        form1.addComponent(rssFeedList);
        } 
         public void startApp() {
        String url = "rss URL";
        ParseThread myThread = new ParseThread(this);
        //this will start the second thread
         myThread.getXMLFeed(url);
          } 
      public void pauseApp() {
       }
                 public void destroyApp(boolean unconditional) {
        }
                 public void DisplayError(Exception error) {
        Dialog validDialog = new Dialog("Alert");
        validDialog.setScrollable(false);
        validDialog.setScrollable(false);
        // set timeout milliseconds
        validDialog.setTimeout(5000);
        //pass the alert text here
        TextArea textArea = new TextArea(error.getMessage());
        textArea.setFocusable(false);
        textArea.setScrollVisible(false);
        validDialog.addComponent(textArea);
        validDialog.show(0, 100, 10, 10, true);
        }
       public void addNews(RssModel newsItem) {
        rssFeed.addElement(newsItem);
        //to handle actions on the list we need to set the actionListener
        rssFeedList.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                List source = (List) ae.getSource();
            }
          });
        form1.show();
         }
    public void actionPerformed(ActionEvent ae) {
        if (ae.getCommand() == cmdExit) {
            destroyApp(true);
            notifyDestroyed();
           }
          }
           }
A Model Class:
import com.sun.lwuit.Image;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author pavan
 */
public class RssModel {
 
    private String title;
    private Image image;
    public RssModel(String title){
        this.title=title;
       // this.image=image;
     
    }
 
    public String getTitle(){
        return title;
    }
    /* public Image getImage(){
        return image;
    }
    * */
 
   }
 RssParsing Class:
import com.sun.lwuit.Image;
import org.kxml2.io.*;
import java.io.*;
import javax.microedition.io.*;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParser;
public class ParseThread {
    protected RssMidlet parentMidlet;
    private Image image;
    private String title;
    public ParseThread(RssMidlet parent) {
        parentMidlet = parent;
    }
    public void getXMLFeed(final String url) {
        Thread t = new Thread() {
            public void run() {
                HttpConnection myConnection = null;
                try {
                    myConnection = (HttpConnection) Connector.open(url);


                    InputStream stream = myConnection.openInputStream();
                    ParseXMLFeed(stream);
                } catch (Exception error) {
                    parentMidlet.DisplayError(error);
                } finally {
                    try {
                        if (myConnection != null) {
                            myConnection.close();
                        }
                    } catch (IOException eroareInchidere) {
                        parentMidlet.DisplayError(eroareInchidere);
                    }
                }
            }
        };
        t.start();
    }
    private void ParseXMLFeed(InputStream input)
            throws IOException, XmlPullParserException {
        InputStreamReader isr = new InputStreamReader(input);
        KXmlParser myParser = null;
        try {
            myParser = new KXmlParser();

            myParser.setInput(isr);
            myParser.nextTag();
            System.out.println("nextTag");
            myParser.require(XmlPullParser.START_TAG, null, "rss");
            myParser.nextTag();
            myParser.require(XmlPullParser.START_TAG, null, "channel");
            myParser.nextTag();
            myParser.require(XmlPullParser.START_TAG, null, "title");
        } catch (Exception e) {
        }
        while (myParser.getEventType() != XmlPullParser.END_DOCUMENT) {
            String name = myParser.getName();
            if (name.equals("channel")) {
                break;
            }
            if (name.equals("item")) {
                if (myParser.getEventType() != XmlPullParser.END_TAG) {
                    myParser.nextTag();
                    title = myParser.nextText();
                    //myParser.nextTag();
                    // String link = myParser.nextText();
                    // myParser.nextTag();
                    // String imageurl = myParser.nextText();
                    // ImageClass ic = new ImageClass();
                    // image = ic.getImage(parentMidlet, imageurl.trim());

                    RssModel model = new RssModel(title);
                    parentMidlet.addNews(model);
                }
            } else {
                myParser.skipSubTree();
            }
            myParser.nextTag();
           }
         input.close();
           }
          }
Finally
NewsListCellRenderer :
You can Create this class by Referring This URL(Just Copy the ContactsRenderer Class File)
Here is the Sample:

public class NewsListCellRenderer extends Container implements ListCellRenderer {
      public NewsListCellRenderer() {  }
    public Component getListCellRendererComponent(List list, Object value, int i, boolean bln)              {}    
}

Thanks.........................





Sunday 4 November 2012

Blackberry SliderBar(SeekBar) Creation

This article will hepls you to Create a SliderBar on BlackBerry Screen,You can use the SliderBar for Controlling a Volume etc...According to your Actual Requirement

To Build this Application you require the below Classes
1)SliderApp: This is the Main Class.The Program Execution will Starts from here.

import net.rim.device.api.ui.UiApplication;

public class SliderApp extends UiApplication {
private static SliderApp app;
private SliderScreen screen;
public SliderApp(){
screen=new SliderScreen();
pushScreen(screen);
}
public static void main(String args[]){
app=new SliderApp();
app.enterEventDispatcher();
}
}



2)SliderScreen:You can get the Complete Code of this class below.
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;

public class SliderScreen extends MainScreen  {
 private SliderField slider;
 private  HorizontalFieldManager manager;
 public SliderScreen(){
            slider = new SliderField(
Bitmap.getBitmapResource("slider2_thumb_normal.png"),
Bitmap.getBitmapResource("slider2_progress_normal.png"),
Bitmap.getBitmapResource("slider2_base_normal.png"),
Bitmap.getBitmapResource("slider2_thumb_focused.png"),
Bitmap.getBitmapResource("slider2_progress_focused.png"),
Bitmap.getBitmapResource("slider2_base_focused.png"), 8, 4,
8, 8, FOCUSABLE);
manager = new HorizontalFieldManager();
manager.add(slider);
setStatus(manager);
      }

      }
3)SliderField: You can get the Complete Code Click Here
Copy and Paste the Code.


Note: You can Download the Slider Images Click Here .

Check the Package Structure and Output in  below ScreenShots:

Package Structure:




OutPut:





LWUIT Tabs Creation in j2me

You can check the Complete Code to Create LWUITTabs here

To Successfully Execute this Application you need to  Download the LWUIT jar File from Here

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.Tabs;
import com.sun.lwuit.layouts.BorderLayout;
import javax.microedition.midlet.MIDlet;

/**
 * @author pavan
 */
public class TabsMidlet extends MIDlet {

    private Tabs tabs;
    private List tab1List;
    private List tab2List;
    private List tab3List;
    private List tab4List;
    private Form form;
    private String[] items1 = {"Item1", "Item2", "Item3"};
    private String[] items2 = {"Item4", "Item5", "Item6"};
    private String[] items3 = {"Item7", "Item8", "Item9"};
    private String[] items4 = {"Item1", "Item2", "Item3"};

    public TabsMidlet() {
       
        Display.init(this);

        form=new Form();
        tab1List = new List(items1);
        tab2List = new List(items2);
        tab3List = new List(items3);
        tab4List = new List(items4);
        tabs = new Tabs();
        tabs.addTab("Tab1", tab1List);
        tabs.addTab("Tab2", tab2List);
        tabs.addTab("Tab3", tab3List);
        tabs.addTab("Tab4", tab4List);
        tabs.setChangeTabOnFocus(true);
        form.setLayout(new BorderLayout());
        form.setScrollable(false);
        form.addComponent(BorderLayout.CENTER, tabs);
        }

    public void startApp() {
                form.show();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}

Wednesday 24 October 2012

HTML Text Extraction in J2me

This article will helps you to Extract a Text from a Html Stringin J2me using HtmlComponent.You need to Provide the Input as Html String to this Sample Example.Then the output will be Pure Text.

Check the Sample Code Below:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.html.HTMLComponent;
import javax.microedition.midlet.MIDlet;
/**
 * @author pavan
 */
public class HtmlMidlet extends MIDlet {
    public void startApp() {
        Display.init(this);
        Form f = new Form("HtmlComponent");
        String html = "<p>HTMl Text Extraction </P><p>Html Text Extraction</p>";
        HTMLComponent com = new HTMLComponent();
        com.setBodyText(html);
        f.addComponent(com);
        f.show();
    }
    public void pauseApp() {
    }
    public void destroyApp(boolean unconditional) {
     }
     }

Note:
1)If you have an Image tag in Html String.Then you can also display  an Image on Screen by Using the below Statement
//com.setShowImages(true);
2)To execute the above Application you need LWUIT jar file.You can download the jar file Here

Creating a HyperLink in j2me

This article will  helps you to display a Hyperlink on (LCDUI User Interface) Form Screen for a WebURL.

If an user clicks on the link it will opens the Hyperlink on  a Phone Default Browser.

You Can find the Complete Code Below:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
/**
 * @author pavan
 */
public class HyperLinkMidlet extends MIDlet {
     String url = "http://www.google.com";
    private Display display;
    private StringItem stringItem;
    private Form form;
     Command com ;
    public HyperLinkMidlet() {
        form = new Form("HyperLink");
                com = new Command("Set", Command.ITEM, 1);
        stringItem = new StringItem("Click Here: ", "Set", Item.HYPERLINK);
    }
    public void startApp() {
        display = Display.getDisplay(this);
         stringItem.setText(url);
        stringItem.setDefaultCommand(com);
        form.append(stringItem);
        display.setCurrent(form);  
        stringItem.setItemCommandListener(new ItemCommandListener() {
            public void commandAction(Command c, Item item) {
                if (c == com) {
                    try {
                        platformRequest(url);
                    } catch (ConnectionNotFoundException ex) {
                    }
                }
            }
        });
 
       }
        public void pauseApp() {
         }
       public void destroyApp(boolean unconditional) {
      }
 
      }

Monday 22 October 2012

ShoutCasting Internet Radio Streaming on BlackBerry

In this Article ,I'm Providing you few Important Links to develop an Online Internet Radio Streaming and playing Mp3 files on a BlackBerry Screen.

You can Check those Links Below:



Using the above two Links you can Successfully Develope the Application


Nokia(j2me) RssFeed(XML) Reader Application using LCDUI(UserInterface API)

This article will helps you to develope  an RssFeed Reader (XML) for Nokia Mobile.
If you run this Application Initially, you will be able to display a (LCDUI User Interface)List Screen.

On this List Screen you will be displayed with an Image as well as a title from Rss-xml file.Moreover,if you click on any List Item you will be Navigate to a Form Screen.

You can Check the Complete Code Below:
Package Structure:


RssMidlet  Class:


import java.util.Vector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class RssMidlet extends MIDlet implements CommandListener {
    private Display myDysplay;
    private List rssList;
    private Vector rssItem;
    private Command cmdExit, cmdDetails;
    private Command m_backCommand;      // The back to header list command
    private Form form;         // The item form
    private RssModel model;
    public RssMidlet() {
        rssItem= new Vector();
        form=new Form("FormScreen");
       
        myDysplay = Display.getDisplay(this);
        m_backCommand = new Command("Back", Command.SCREEN, 1);
        form.addCommand(m_backCommand);
        rssList = new List("RssListScreen", List.IMPLICIT);
        cmdExit = new Command("EXIT", Command.EXIT, 1);
        cmdDetails = new Command("Details", Command.SCREEN, 2);
        rssList.addCommand(cmdExit);
        rssList.addCommand(cmdDetails);
       }
   
                 public void startApp() {
        // XML file url
        String url = "Rss File Here";
        form.setCommandListener(this);
        rssList.setCommandListener(this);
        ParseThread myThread = new ParseThread(this);
        //this will start the second thread
        myThread.getXMLFeed(url);
        Display.getDisplay(this).setCurrent(rssList);
       }
        public void pauseApp() {
        }
        public void destroyApp(boolean unconditional) {
       }
     
public void commandAction(Command command, Displayable displayable) {
        /**
         * Get back to RSS feed headers
         */
        if (command == m_backCommand) {
            myDysplay.setCurrent(rssList);
        }
        if (command == cmdExit) {
            destroyApp(false);
            notifyDestroyed();
        } else if (command == cmdDetails || command == List.SELECT_COMMAND) {
            //get the index of the selected title
            int index = rssList.getSelectedIndex();
            if (index != -1) {
                           Display.getDisplay(this).setCurrent(form);     
            }
             
             
        }
    }
    //method called by the parsing thread
    public void addItems(RssModel model) {
        rssItem.addElement(rssItem);
       
        rssList.append(model.getTitle(), model.getImage());
     
        myDysplay.setCurrent(rssList);
    }
    public void DisplayError(Exception error) {
        Alert errorAlert = new Alert("Error", error.getMessage(), null, null);
        errorAlert.setTimeout(Alert.FOREVER);
        myDysplay.setCurrent(errorAlert, rssList);
    }
}

ParseThread:
import org.kxml2.io.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.Image;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParser;
              public class ParseThread {
    protected RssMidlet parentMidlet;
    private String imageurl;
    private Image image;
    private String readUrl;
    private String srcUrl;
    public ParseThread(RssMidlet parent) {
        parentMidlet = parent;
    }
    public void getXMLFeed(final String url) {
        Thread t = new Thread() {
            public void run() {
                HttpConnection myConnection = null;
                try {
                    myConnection = (HttpConnection) Connector.open(url);
                    InputStream stream = myConnection.openInputStream();
                    ParseXMLFeed(stream);
                } catch (Exception error) {
                    parentMidlet.DisplayError(error);
                } finally {
                    try {
                        if (myConnection != null) {
                            myConnection.close();
                        }
                    } catch (IOException eroareInchidere) {
                        parentMidlet.DisplayError(eroareInchidere);
                    }
                }
            }
        };
        t.start();
    }
             private void ParseXMLFeed(InputStream input) throws IOException, XmlPullParserException {
        System.out.println("ParseXMLFeed");
        Reader dataReader = new InputStreamReader(input);
        KXmlParser myParser = null;
        try {
            myParser = new KXmlParser();
        } catch (Exception e) {
            //System.out.println("hiiii" + e);
        }
        myParser.setInput(dataReader);

        myParser.nextTag();
        myParser.require(XmlPullParser.START_TAG, null, "rss");
        myParser.nextTag();
        myParser.require(XmlPullParser.START_TAG, null, "channel");
        myParser.nextTag();
        myParser.require(XmlPullParser.START_TAG, null, "title");
        while (myParser.getEventType() != XmlPullParser.END_DOCUMENT) {
            String name = myParser.getName();
            if (name.equals("channel")) {
                break;
            }
            if (name.equals("item")) {
                if (myParser.getEventType() != XmlPullParser.END_TAG) {
                    myParser.nextTag();
                    String title = myParser.nextText();
                    System.out.println("Title" + title);
                    myParser.nextTag();
                    String link = myParser.nextText();
                    System.out.println("Link" + link);
                    myParser.nextTag();
                    String pubDate = myParser.nextText();
                    myParser.nextTag();
                    String ptext = myParser.nextText();//(<p>some text</p>)
                    System.out.println("PTEXT>>>" + ptext);
                            //Image src Value from ptext  
                    if (ptext.indexOf("src") != -1) {
                        int pTagIndex = ptext.indexOf("p");
                        int srcIndex1 = ptext.indexOf("src", pTagIndex);
                        int httpIndex1 = ptext.indexOf("/", srcIndex1);
                        int quotesIndex1 = ptext.indexOf("\"", httpIndex1);
                        srcUrl = ptext.substring(httpIndex1, quotesIndex1);
                        System.out.println("srcUrl " + srcUrl);
                        boolean containsWhitespace = srcUrl.trim().indexOf(" ") != -1;
                        if (containsWhitespace == true) {
                            displayDefaultImage();

                        } else {
                            //imageurl = "http://www...." + srcUrl;
                         
                            ImageClass ic = new ImageClass();
                            image = ic.getImage(parentMidlet, srcUrl.trim());
                        }

                    } else {
                        System.out.println("Default");
                        displayDefaultImage();
                    }
                    //check imagesrc contains any whitespace characters or not
                    RssModel model = new RssModel(title, image);
                    parentMidlet.addItems(model);
                    }
                     } else {
                     myParser.skipSubTree();
                      }
                    myParser.nextTag();
                       }
                    input.close();
                    }
                    private void displayDefaultImage() {
                 try {
                  image = Image.createImage("/res/logo.png");
              } catch (IOException ex) {
                 ex.printStackTrace();
                  }
                  }
                  }
ImageClass: it will return the image class reference


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.DataInputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Image;
/**
 *
 * @author welcome
 */
public class ImageClass {
    private RssMidlet parentMidlet;
    private DataInputStream is = null;
    private Image img = null;
    private Display display;
    public Image getImage(RssMidlet parentMidlet, String imageurl) {
        this.parentMidlet = parentMidlet;
        display = Display.getDisplay(parentMidlet);
        try {
            HttpConnection c = (HttpConnection) Connector.open(imageurl);
            int len = (int) c.getLength();
            if (len > 0) {
                is = c.openDataInputStream();
                byte[] data = new byte[len];
                is.readFully(data);
                img = Image.createImage(data, 0, len);
                //img=createThumbnail(img);
            } else {
                showAlert("length is null");
            }
            is.close();
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
            showAlert(e.getMessage());
        }
        return img;
        }
       private void showAlert(String err) {
        Alert a = new Alert("");
        a.setString(err);
        a.setTimeout(Alert.FOREVER);
        display.setCurrent(a);
         }
         }


RssModel Class:

import javax.microedition.lcdui.Image;
public class RssModel {
    private String title;
    private Image image;
    public RssModel(String Title,Image image) {
        title = Title;
        this.image = image;
    }
    public String getTitle() {
        return title;
    }
   
    public Image getImage() {
        return image;
    }
 
    }








Wednesday 17 October 2012

Getting Started with J2me Basic Application

This Article will helps you to Certain  links to download and Install Softwares To work with J2me Series40 Basic Application.

Step-1:You  need to download and Install any Preferred IDE either NetBeans or Eclipse,I've Done with NetBeans IDE 7.1.2.(Link to Download NetBeans IDE Click Here)

Step-2: You need to Download and Install Latest Nokia SDK 2.0 for java to test your Application in  this Simulator.
Link to Download  Click Here (You Need to Download this Nokia SDK 2.0 for Java — for Series 40 apps)

Step-3:After you Install Both ,Open your NetBeans IDE
1)Go to Tools and select java Platform:
2)Click on AddPlatForm:











3)You are Displayed with Nokia SDK 2.0 Simulator,Just select it and click on next:


4)You will be Successfully able to  Integrated your IDE with your Simulator

Step-4: Go to File menu on NetBeans and click NewProject

Choose JavaME From Categories and Choose Mobile Application From Projects and Click Next



Step-5:Give your Project Name and Check set as Main Project and Create Hello Midlet like below



Step-6:Select your Emulator in this Step like below and click on finish



Step-7: Finally you should code your app like this:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hello;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.*;
/**
 * @author welcome
 */
public class HelloMidlet extends MIDlet {
    private Display display;
    private Form form;
    //Constructor
    public HelloMidlet() {
        form = new Form("HelloWorld");
    }
    public void startApp() {
        display = Display.getDisplay(this);
        form.setTicker(new Ticker("Hello World"));
        display.setCurrent(form);
    }
   public void pauseApp() {
    }
    public void destroyApp(boolean unconditional) {
    }
    }
Step-8: After you Coded the Midlet Class ,Right Click on your Project and you need to Run your Application



Note:You can also Create your Midlet Class Manually like this ,Right click on your Source and select new Midlet




Midlet: It is a Class just like Main class in Core Java.
In  Java-me  The Program Execution will start from Midlet Class
It is Having Life Cycle Methods
Few are: 
1)StartApp()
2)PauseApp()
3)DestroyApp()












Tuesday 16 October 2012

Youtube Video Streaming in J2me


As far as My knowledge is Concerned in j2me,we cannot perform Direct Http based Streaming.The Manager(javax.microedition.media.Manager) class  method doesn't support HttpStreaming URL(if we Place we will be getting Invalid URL).

If you want to stream and play youtube videos,try to parse and get the RTSP link from your youtube URL,Because in java-me we can successfully stream and play RTSP Protocol based URL.

This article will provide you  the Complete Code to Stream and Play RTSP URL:

Note: I've tested the code on Nokia SymbianBelleSDK 1.1

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class ExampleStreamingMIDlet extends MIDlet {
public List list;
String url="rtsp://v1.cache5.c.youtube.com/CjYLENy73wIaLQm8E_KpEOI9cxMYDSANFEIJbXYtZ29vZ2xlSARSBXdhdGNoYLm0hv_ig5HRTww=/0/0/0/video.3gp";
public ExampleStreamingMIDlet() {
   
    list = new List("Accueil", List.IMPLICIT);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
    VideoCanvas VC = new VideoCanvas(this,url);
    Display.getDisplay(this).setCurrent(VC); }
}


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Ticker;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VideoControl;

public class VideoCanvas extends Canvas implements PlayerListener, CommandListener {

private ExampleStreamingMIDlet midlet = null;
private Command start = new Command("Start",Command.OK,0);
private Command stop = new Command("Stop",Command.OK,0);
private Command back = new Command("Back",Command.OK,0);
private Command exit = new Command("Exit",Command.BACK,0);
private String url;
private String status = "Press left softkey";
private String status2 = "";
private Player player = null;
private VideoControl control = null;

/**
* Constructor
*
* @param midlet
*/

public VideoCanvas(ExampleStreamingMIDlet midlet, String url) {
this.midlet = midlet;
this.url = url;
addCommand(start);
addCommand(stop);
addCommand(back);
addCommand(exit);
setCommandListener(this);
this.setFullScreenMode(true);
}

public void commandAction(Command c, Displayable arg1) {
if(c == start) {
start();
}
else if(c == stop) {
stop();
}
else if(c == exit) {
midlet.notifyDestroyed();
}
else if(c == back) {
Display.getDisplay(midlet).setCurrent(midlet.list);
}

}

/**
* Paint
*/

protected void paint(Graphics g) {
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
g.drawString(status2,0,0,Graphics.LEFT|Graphics.TOP);
g.drawString(status,getWidth(),getHeight(),Graphics.RIGHT|Graphics.BOTTOM);
}

/**
* Start
*
*/

public void start() {
try{
       
           Player player = Manager.createPlayer(url);
   player.addPlayerListener(this);
  player.realize();

 
   control = (VideoControl)player.getControl("VideoControl");
   if (control != null) {
    control.initDisplayMode(VideoControl.USE_DIRECT_VIDEO,this);
    control.setDisplaySize(176,144);
    int width = control.getSourceWidth();
    int height = control.getSourceHeight();
    status2 = "Before: SW=" + width + "-SH=" + height + "-DW=" + control.getDisplayWidth() + "-DH=" + control.getDisplayHeight();
   }

   player.start();
}
catch(Exception e) {
Alert erro = new Alert("Erro",e.getMessage(),null,AlertType.ERROR);
Display.getDisplay(midlet).setCurrent(erro);
}
}

public void stop() {
if(player != null) {
player.deallocate();
player.close();
}
}

public void playerUpdate(Player p, String s, Object o) {
status = s;

if(p.getState() == Player.STARTED) { int width = control.getDisplayWidth();
                        int height = control.getDisplayHeight();     control.setDisplayLocation((getWidth() - width)/2,(getHeight() -    height)/2);
control.setVisible(true);
status = s + ": DW=" + width + "-DH=" + height + "-SW=" +     control.getSourceWidth() + "-SH=" + control.getSourceHeight();
}
repaint();
setTitle(status);
}
 
      }

Saturday 13 October 2012

RssFeed Reader for BlackBerry Application

Nowadays Most of the Web Sites are using RssFeeds for their Content,So It is Important to know that  How to read and Parse an Rss File.
This application is designed to read and Parse  an RssFile(Input is RssFile) and Finally it displays a title and an Image on the Blackberry Screen....

The Project Package Structure on Eclipse :


You can check the Complete Code Here:

The Main Class:
import net.rim.device.api.ui.UiApplication;
public class RssApp extends UiApplication {
private static RssApp app;
public RssScreen screen;
public static void main(String args[]) {
app = new RssApp();
app.enterEventDispatcher();
}
//Constructor
public RssApp() {
screen = new RssScreen();
pushScreen(screen);
}
 }

RssScreen:
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;
      public class RssScreen extends MainScreen implements ListFieldCallback, FieldChangeListener {
private ListField _list;
private VerticalFieldManager mainManager;
private VerticalFieldManager subManager;
public long mycolor;
private Vector listElements = new Vector();
private Connection _connectionthread;
private Vector listLink;
private Vector listImage;
private String link;
public RssScreen() {
listLink = new Vector();
listImage = new Vector();
          //Background Image
final Bitmap backgroundBitmap = Bitmap
.getBitmapResource("blackbackground.png");
mainManager = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL
| Manager.NO_VERTICAL_SCROLLBAR) {
public void paint(Graphics graphics) {
graphics.drawBitmap(0, 0, Display.getWidth(),
Display.getHeight(), backgroundBitmap, 0, 0);
super.paint(graphics);
}
};
subManager = new VerticalFieldManager(Manager.VERTICAL_SCROLL
| Manager.VERTICAL_SCROLLBAR) {
protected void sublayout(int maxWidth, int maxHeight) {
int displayWidth = Display.getWidth();
int displayHeight = Display.getHeight();
super.sublayout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
};
add(mainManager);
_list = new ListField()
{
protected boolean navigationClick(int status, int time) {
return true;
}
public void paint(Graphics graphics)
{
graphics.setColor((int) mycolor);
super.paint(graphics);
}
};
mycolor = 0x00FFFFFF;
_list.invalidate();
_list.setEmptyString("* Feeds Not Available *", DrawStyle.HCENTER);
_list.setRowHeight(70);
_list.setCallback(this);
mainManager.add(subManager);
listElements.removeAllElements();
_connectionthread = new Connection();
_connectionthread.start();
}
          /*RssFileReading in a Seperate Thread*/
private class Connection extends Thread {
public Connection() {
super();
}
public void run() {
Document doc;
StreamConnection conn = null;
InputStream is = null;
try {
conn = (StreamConnection) Connector .open("your Rss Input File.xml"
+ ";deviceside=true");
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
docBuilderFactory.setCoalescing(true);
DocumentBuilder docBuilder = docBuilderFactory
.newDocumentBuilder();
docBuilder.isValidating();
is = conn.openInputStream();
doc = docBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList listImg = doc.getElementsByTagName("title");
for (int i = 0; i < listImg.getLength(); i++) {
Node textNode = listImg.item(i).getFirstChild();
listElements.addElement(textNode.getNodeValue());
}
NodeList list = doc.getElementsByTagName("image");
for (int a = 0; a < list.getLength(); a++) {
Node textNode1 = list.item(a).getFirstChild();
String imageurl = textNode1.getNodeValue();
Bitmap image = GetImage.connectServerForImage(imageurl
.trim() + ";deviceside=true");
listImage.addElement(image);
}
/*NodeList listlink = doc.getElementsByTagName("link");
for (int j = 0; j < listlink.getLength(); j++) {
Node textNode1 = listlink.item(j).getFirstChild();
link = textNode1.getNodeValue();
listLink.addElement(link);
}*/ 
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException ignored) {
}
}
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_list.setSize(listElements.size());
subManager.add(_list);
invalidate();
}
});
} }
/*This Method is Invoked for Each title on RssFile*/
public void drawListRow(ListField list, Graphics g, int index, int y,
int width) {
String title = (String) listElements.elementAt(index);
Bitmap image = (Bitmap) listImage.elementAt(index);
try {
int LEFT_OFFSET = 2;
int TOP_OFFSET = 8;
int xpos = LEFT_OFFSET;
int ypos = TOP_OFFSET + y;
int w = image.getWidth();
int h = image.getHeight();
g.drawBitmap(xpos, ypos, w, h, image, 0, 0);
xpos = w + 20;
g.drawText(title, xpos, ypos);
} catch (Exception e) {
e.printStackTrace();
}
}
public Object get(ListField list, int index) {
return listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string) {
return listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list) {
return Display.getWidth();
}
public void insert(String toInsert, int index) {
listElements.addElement(toInsert);
}
public void fieldChanged(Field field, int context) {
}
}

UtilClass: This Class will return a Bitmap reference

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;

public class GetImage {
public static Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
// System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
  }

Thanks..............