Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
New Developer
mdwheaton
Posts: 37
Registered: ‎07-15-2008
My Device: Not Specified

Display HTML in a Screen Field

I have searched this forum many times, and seen many partial examples.

Does anyone have a simple example to take a snippet of HTML and allow it to be rendered on a regular MainScreen, and NOT within the BB Browser?

 

Something like ...

I'm using OS4.5 or below and have seen some examples that start off like this...

 

BrowserContent content = RenderingSession.getNewInstance().getBrowserContent(?,?,?,?);

String htmlString = "<html><head></head><body>Hello World!</body></html>";

//somehow add this content to the field

Field field = content.getDisplayableContent(); add(fld);

 

 I'm not sure what to fill in.

 

Does anyone have a simple, complete example, and not links to other incomplete examples?

 

Greatly appreciated!

 

Please use plain text.
Developer
johnbibs
Posts: 905
Registered: ‎02-07-2009
My Device: BlackBerry Torch 9800

Re: Display HTML in a Screen Field

Please use plain text.
New Developer
mdwheaton
Posts: 37
Registered: ‎07-15-2008
My Device: Not Specified

Re: Display HTML in a Screen Field

This invokes the Browser...I want the content to display in a field on a screen with other "normal" fields.
Please use plain text.
Developer
johnbibs
Posts: 905
Registered: ‎02-07-2009
My Device: BlackBerry Torch 9800

Re: Display HTML in a Screen Field

Please use plain text.
New Developer
kelumkps
Posts: 14
Registered: ‎09-17-2009
My Device: Not Specified

Re: Display HTML in a Screen Field

 

You can implement javax.microedition.io.HttpConnection interface so that it takes your htmlString like this.

 

public class HttpConnectionImpl implements HttpConnection {
private DataInputStream dataInput;
private InputStream in;
private String encoding = "text/html";

public HttpConnectionImpl(String htmlString) {
try {
in = new ByteArrayInputStream(htmlString.getBytes("UTF-8"));
dataInput = new DataInputStream(in);
} catch (Exception e) {
System.out.println("HttpConnectionImpl : Exception : " + e);
}

}

// implement rest of the methods of HttpConnection interface with dummy methods


}

 

 

 Then you can pass an object of this implementation to get the field as follows;

 

String htmlString = "<html><head></head><body>Hello World!</body></html>";

HttpConnection connection = new HttpConnectionImpl(htmlString);

BrowserContent content = RenderingSession.getNewInstance().getBrowserContent(connection,?,?);

Field field = content.getDisplayableContent();

add(field);

 

 

 

 Regards,

 

-Kelum-

 

 

 

 

Please use plain text.
Developer
kudos12
Posts: 35
Registered: ‎08-07-2009
My Device: Not Specified

Re: Display HTML in a Screen Field

Hi,

 

I am trying to follow the steps you have provided. But i am getting error as " 

HTTP Error 0: An error occurred while communicating with the origin server. Please try again."

 

I have the follwoing sampel code divided into three parts

 

First class: connection maker

 

public class HttpConnectionImpl implements HttpConnection { private DataInputStream dataInput; private InputStream in; private String encoding = "text / html";//providing space between "/" so that i can post this message. public HttpConnectionImpl(String htmlString) { try { in = new ByteArrayInputStream(htmlString.getBytes("UTF-8")); dataInput = new DataInputStream(in); } catch (Exception e) { System.out.println("HttpConnectionImpl : Exception : " + e); } } public long getDate() throws IOException { // TODO Auto-generated method stub return 0; } public long getExpiration() throws IOException { // TODO Auto-generated method stub return 0; } public String getFile() { // TODO Auto-generated method stub return null; } public String getHeaderField(String arg0) throws IOException { // TODO Auto-generated method stub return null; } public String getHeaderField(int arg0) throws IOException { // TODO Auto-generated method stub return null; } public long getHeaderFieldDate(String arg0, long arg1) throws IOException { // TODO Auto-generated method stub return 0; } public int getHeaderFieldInt(String arg0, int arg1) throws IOException { // TODO Auto-generated method stub return 0; } public String getHeaderFieldKey(int arg0) throws IOException { // TODO Auto-generated method stub return null; } public String getHost() { // TODO Auto-generated method stub return null; } public long getLastModified() throws IOException { // TODO Auto-generated method stub return 0; } public int getPort() { // TODO Auto-generated method stub return 0; } public String getProtocol() { // TODO Auto-generated method stub return null; } public String getQuery() { // TODO Auto-generated method stub return null; } public String getRef() { // TODO Auto-generated method stub return null; } public String getRequestMethod() { // TODO Auto-generated method stub return null; } public String getRequestProperty(String arg0) { // TODO Auto-generated method stub return null; } public int getResponseCode() throws IOException { // TODO Auto-generated method stub return 0; } public String getResponseMessage() throws IOException { // TODO Auto-generated method stub return null; } public String getURL() { // TODO Auto-generated method stub return null; } public void setRequestMethod(String arg0) throws IOException { // TODO Auto-generated method stub } public void setRequestProperty(String arg0, String arg1) throws IOException { // TODO Auto-generated method stub } public String getEncoding() { // TODO Auto-generated method stub return encoding; } public long getLength() { // TODO Auto-generated method stub return 0; } public String getType() { // TODO Auto-generated method stub return null; } public DataInputStream openDataInputStream() throws IOException { // TODO Auto-generated method stub return dataInput; } public InputStream openInputStream() throws IOException { // TODO Auto-generated method stub return in; } public void close() throws IOException { // TODO Auto-generated method stub } public DataOutputStream openDataOutputStream() throws IOException { // TODO Auto-generated method stub return null; } public OutputStream openOutputStream() throws IOException { // TODO Auto-generated method stub return null; } }

 

 

Second class the screen class

 

public class BrowserScreen extends MainScreen { public BrowserScreen() { LabelField title = new LabelField("Hello World Demo" , LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH); setTitle(title); add(new RichTextField("Hello World!" ,Field.NON_FOCUSABLE)); add(new ActiveRichTextField("<p>abcd</p><p>amber&apos; work is moving ahead</p>")); String test = "<p>abcd</p><p>amber&apos; work is moving ahead</p>"; try { HttpConnection connection = new HttpConnectionImpl(test); BrowserContent content = RenderingSession.getNewInstance().getBrowserContent(connection,null,null); Field field = content.getDisplayableContent(); add(field); }catch (Exception e) { System.out.println("Exceptrion rendering "+e.getMessage()); } } }

 

Third class is the class having main method

 

 

public class BrowserSample extends UiApplication { public static void main(String[] args) { BrowserSample theApp = new BrowserSample(); theApp.enterEventDispatcher(); } public BrowserSample() { pushScreen(new BrowserScreen()); } }

 

Can you please tell me why the renderer is throwing error. I also tried this my implementing RenderingApplication in second class and leaving all unimplemented methods as default. Still got the same error.

 

Please help me in resolving this issue.

 

Thanks,

Regards,

Amber

Please use plain text.
Developer
tek3
Posts: 190
Registered: ‎07-08-2009
My Device: Not Specified

Re: Display HTML in a Screen Field


ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream boutput = new Base64OutputStream( output );
output.write( "data:text/html;base64,".getBytes() );
boutput.write( HTML_STRING.getBytes() ); // HTML_STRING is the string containing your HTML content
boutput.flush();
boutput.close();
output.flush();
output.close();


now i am making use of BrowserField demo example shipped with JDE..

in it i am opening connection to output.toString()

PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(output.toString(), null, null, null, this); //instead of passing url
//pass output.toString() to
//PrimaryResourceFetchThread


now the Field which u will get as
Field field=browserContent.getDisplayableContent();

will be the Field displaying your HTML content...Now add this Field to your mainScreen...
Please use plain text.
Developer
kudos12
Posts: 35
Registered: ‎08-07-2009
My Device: Not Specified

Re: Display HTML in a Screen Field

Hi,

 

Tek3 thanks for your solution ... i have read this solution in your earlier post, but right now was looking for some simple execution. :smileyhappy:

 

kelumkps solution seems to be promising to me.So, i tried that one first.

 

Hi kelumkps, please provide me your views about the code. It will be really very helpfull and simple to find a solution like that one.

 

Right now i am going to implement tek3 solution, but will love to hear something from kelumkps.

 

thanks Tek3

 

Regards,

Amber

Please use plain text.
Developer
kudos12
Posts: 35
Registered: ‎08-07-2009
My Device: Not Specified

Re: Display HTML in a Screen Field

Hi Tek3,

 

I have implemented your solution it was working fine, like a charm.

Still i am away from my exact requirment. May be you can help me in sorting this out.

 

Requirment: On opening application, i have to show a list, fetched from an HTTP xml. User will click on any one of the item of list. On click i have fetch another set of information through HTTP in form of XML.Parsing xml i have to show content of one of nodes of xml which contains some HTML codes, which are cause of problem for me and for those HTML cods i am here. :smileyhappy:

 

I have made a small sample application of few lines. Please have a look at it andhelp me how i can acheive my requirment.

 

 

First class which is having main

public class BrowserFieldSample extends UiApplication { public static void main(String[] args) { BrowserFieldSample theApp = new BrowserFieldSample(); theApp.enterEventDispatcher(); } public BrowserFieldSample() { pushScreen(new SampleScreen()); //new BrowserFieldDemo(); //invokeDemo(); } }

 

 Screen class which shows a field which ask for click

 

 

public class SampleScreen extends MainScreen { public SampleScreen() { LabelField lb = new LabelField("Click Here",Field.FOCUSABLE|Field.HIGHLIGHT_FOCUS) { protected boolean navigationClick(int status, int time) { new BrowserFieldDemo(); return super.navigationClick(status, time); } }; add(lb); } }

 

 Third class which is changed version of browserdemo

 

 

public class BrowserFieldDemo implements RenderingApplication { private static final String REFERER = "referer"; private RenderingSession _renderingSession; private HttpConnection _currentConnection; private MainScreen _mainScreen; private String content; public BrowserFieldDemo() { _mainScreen = new MainScreen(); UiApplication.getUiApplication().pushScreen(_mainScreen); _renderingSession = RenderingSession.getNewInstance(); content = "<p>abcd</p><p>amber&apos;s work is moving ahead.<br/> Its a good sign yahoo yup</p>"; //String HTML_STRING = "<p>abcd</p><p>amber&apos;s work is moving ahead</p>"; processContent(); } void processContent() { try{ ByteArrayOutputStream output = new ByteArrayOutputStream(); Base64OutputStream boutput = new Base64OutputStream( output ); output.write( "data:text/html;base64,".getBytes() ); boutput.write( content.getBytes() ); // HTML_STRING is the string containing your HTML content boutput.flush(); boutput.close(); output.flush(); output.close(); fetchPrimaryResource(output.toString(), null, null, null, this); } catch (Exception e) { System.out.println(e.getMessage()); } } void processConnection(HttpConnection connection, Event e) { // Cancel previous request. if (_currentConnection != null) { try { _currentConnection.close(); } catch (IOException e1) { } } _currentConnection = connection; BrowserContent browserContent = null; try { browserContent = _renderingSession.getBrowserContent(connection, this, e); if (browserContent != null) { Field field = browserContent.getDisplayableContent(); if (field != null) { synchronized (Application.getEventLock()) { _mainScreen.deleteAll(); _mainScreen.add(new LabelField("Welcome .....")); _mainScreen.add(field); } } browserContent.finishLoading(); } } catch (RenderingException re) { } finally { } } public Object eventOccurred(Event event) { return null; } public int getAvailableHeight(BrowserContent browserField) { // Field has full screen. return Display.getHeight(); } public int getAvailableWidth(BrowserContent browserField) { // Field has full screen. return Display.getWidth(); } public int getHistoryPosition(BrowserContent browserField) { // No history support. return 0; } public String getHTTPCookie(String url) { // No cookie support. return null; } public HttpConnection getResource( RequestedResource resource, BrowserContent referrer) { return null; } public void invokeRunnable(Runnable runnable) { (new Thread(runnable)).start(); } public void fetchPrimaryResource(String url, HttpHeaders requestHeaders, byte[] postData,Event event, BrowserFieldDemo application) { HttpConnection connection = Utilities.makeConnection(url, requestHeaders, postData); processConnection(connection, event); } }

 

 

Please help me out from this. I think there is some mistake made my me and i think the eventDispatcher is not getting vailable to the BrowserContent. How i can make it availabel to him.

 

Regards,

Amber

Please use plain text.
New Developer
kelumkps
Posts: 14
Registered: ‎09-17-2009
My Device: Not Specified

Re: Display HTML in a Screen Field

Hikudos12

 

In my previous post I forgot to tell about implementing rest of the methods of javax.microedition.io.HttpConnection interface. Don't implement those methods to return null values. You can see below how I implemented it.

 

 

public class HttpConnectionImpl implements HttpConnection { private long streamLength = 7000; private DataInputStream dataInput; private InputStream in; private String encoding = "text/html"; public HttpConnectionImpl(String data) { try { in = new ByteArrayInputStream(data.getBytes("UTF-8")); dataInput = new DataInputStream(in); } catch (Exception e) { System.out.println("HttpConnectionImpl : Exception : " + e); } } public String getURL() { return ""; } public String getProtocol() { return ""; } public String getHost() { return ""; } public String getFile() { return ""; } public String getRef() { return ""; } public String getQuery() { return ""; } public int getPort() { return 0; } public String getRequestMethod() { return ""; } public void setRequestMethod(String s) throws IOException { } public String getRequestProperty(String s) { return ""; } public void setRequestProperty(String s, String s1) throws IOException { } public int getResponseCode() throws IOException { return 200; } public String getResponseMessage() throws IOException { return ""; } public long getExpiration() throws IOException { return 0; } public long getDate() throws IOException { return 0; } public long getLastModified() throws IOException { return 0; } public String getHeaderField(String s) throws IOException { return ""; } public int getHeaderFieldInt(String s, int i) throws IOException { return 0; } public long getHeaderFieldDate(String s, long l) throws IOException { return 0; } public String getHeaderField(int i) throws IOException { return ""; } public String getHeaderFieldKey(int i) throws IOException { return ""; } public String getType() { return "text/html"; } public String getEncoding() { return encoding; } public long getLength() { return streamLength; } public InputStream openInputStream() throws IOException { return in; } public DataInputStream openDataInputStream() throws IOException { return dataInput; } public void close() throws IOException { } public OutputStream openOutputStream() throws IOException { return new ByteArrayOutputStream(); } public DataOutputStream openDataOutputStream() throws IOException { return new DataOutputStream(new ByteArrayOutputStream()); } }

 

 

 

 Then I slightly modified BrowserFieldDemo class as follows;

 

 

public class BrowserFieldDemo implements RenderingApplication { private String data; private static final String REFERER = "referer"; private RenderingSession renderingSession; private HttpConnection currentConnection; private Field displayableField; private MainScreen mainScreen; public BrowserFieldDemo(String data, MainScreen mainScreen) { this.data = data; this.mainScreen = mainScreen; renderingSession = RenderingSession.getNewInstance(); // enable javascript renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID, RenderingOptions.JAVASCRIPT_ENABLED, true); ResourceFetchThread thread = new ResourceFetchThread(data, null, this); thread.start(); } public void processConnection(HttpConnection connection, Event e) { // cancel previous request if (currentConnection != null) { try { currentConnection.close(); } catch (IOException e1) { } } currentConnection = connection; BrowserContent browserContent = null; try { browserContent = renderingSession.getBrowserContent(connection, this, e); if (browserContent != null) { Field field = browserContent.getDisplayableContent(); if (field != null) { synchronized (Application.getEventLock()) { this.mainScreen.add(field); } } browserContent.finishLoading(); System.out.println("Done loading>>>>>"); } } catch (RenderingException re) { System.out.println("RenderingException : " + re); } catch (Exception ex) { System.out.println("Exception : " + ex); ex.printStackTrace(); } } public Object eventOccurred(Event event) { int eventId = event.getUID(); switch (eventId) { case Event.EVENT_URL_REQUESTED: { ResourceFetchThread thread = new ResourceFetchThread(data, null, this); thread.start(); break; } case Event.EVENT_BROWSER_CONTENT_CHANGED: { break; } case Event.EVENT_REDIRECT: { RedirectEvent e = (RedirectEvent) event; String referrer = e.getSourceURL(); switch (e.getType()) { case RedirectEvent.TYPE_SINGLE_FRAME_REDIRECT: // show redirect message Application.getApplication().invokeAndWait(new Runnable() { public void run() { Status.show("You are being redirected to a different page..."); } }); break; case RedirectEvent.TYPE_JAVASCRIPT&colon; break; case RedirectEvent.TYPE_META: // MSIE and Mozilla don't send a Referer for META Refresh. referrer = null; break; case RedirectEvent.TYPE_300_REDIRECT: // MSIE, Mozilla, and Opera all send the original // request's Referer as the Referer for the new // request. Object eventSource = e.getSource(); if (eventSource instanceof HttpConnection) { referrer = ((HttpConnection) eventSource).getRequestProperty(REFERER); } break; } HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setProperty(REFERER, referrer); ResourceFetchThread thread = new ResourceFetchThread(this.data, event, this); thread.start(); break; } case Event.EVENT_CLOSE: // TODO: close the appication break; case Event.EVENT_SET_HEADER: // no cache support case Event.EVENT_SET_HTTP_COOKIE: // no cookie support case Event.EVENT_HISTORY: // no history support case Event.EVENT_EXECUTING_SCRIPT: // no progress bar is supported case Event.EVENT_FULL_WINDOW: // no full window support case Event.EVENT_STOP: // no stop loading support default: } return null; } /** * @see */ public int getAvailableHeight(BrowserContent browserField) { // field has full screen return Graphics.getScreenHeight(); } /** * @see */ public int getAvailableWidth(BrowserContent browserField) { // field has full screen return Graphics.getScreenWidth(); } /** * @see */ public int getHistoryPosition(BrowserContent browserField) { // no history support return 0; } public String getHTTPCookie(String url) { // no cookie support return null; } public HttpConnection getResource(RequestedResource resource, BrowserContent referrer) { if (resource == null) { return null; } // check if this is cache-only request if (resource.isCacheOnly()) { // no cache support return null; } String url = resource.getUrl(); if (url == null) { return null; } // if referrer is null we must return the connection if (referrer == null) { // HttpConnection connection = Utilities.makeConnection(resource.getUrl(), resource.getRequestHeaders(), null); HttpConnection connection = new HttpConnectionImpl(url); return connection; } /*else { // if referrer is provided we can set up the connection on a separate thread SecondaryResourceFetchThread.enqueue(resource, referrer); }*/ return null; } /** * @see */ public void invokeRunnable(Runnable runnable) { (new Thread(runnable)).run(); } public Field getDisplayableField() { if (displayableField == null) displayableField = new NullField(); return displayableField; } } class ResourceFetchThread extends Thread { private MBrowserField application; private Event event; private String data; ResourceFetchThread(String data, Event event, MBrowserField application) { this.data = data; this.application = application; this.event = event; } public void run() { HttpConnection connection = new HttpConnectionImpl(this.data); this.application.processConnection(connection, this.event); } }

 

 

 

 I passed the required HTML String and a MainScreen object to add the browser contents to that object. Try this way and it works for me.

 

Cheers,

 

-Kelum-

 

 

Please use plain text.