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
Contributor
Posts: 34
Registered: ‎10-19-2011
My Device: 9800
My Carrier: sim free
Accepted Solution

BrowserField Encoding problem

Hello! Please, help me! I've spent almost all day, but haven't got success. My BrouserField is showing "????" characters instead of non-English characters.
I need to get XML ribbon, parse it and display in the BrowserFiled.
I'm using such classes:

 

1) WaitScreen - PopupScreen from knowledgebase example

public class WaitScreen extends PopupScreen {
	
    private LabelField _ourLabelField = null;
    
    private WaitScreen(String text) {
        super(new HorizontalFieldManager());
        VerticalFieldManager _vfm = new VerticalFieldManager();
        _ourLabelField = new LabelField(text, Field.FIELD_HCENTER);
        _vfm.add(_ourLabelField);
        this.add(_vfm);
        this.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.BLACK, 225));										 
    }
    
    public static void showScreenAndWait(final Runnable runThis, String text) {
        final WaitScreen thisScreen = new WaitScreen(text);
        Thread threadToRun = new Thread() {
            public void run() {
                // First, Waintdisplay this screen
                UiApplication.getUiApplication().invokeLater(new Runnable() {
                    public void run() {
                        UiApplication.getUiApplication().pushScreen(thisScreen);
                    }
                });
                // Now run the code that must be executed in the Background
                try {
                    runThis.run();
                } catch (Throwable t) {
                    t.printStackTrace();
                    throw new RuntimeException("Exception detected while waiting: " + t.toString());
                }
                // Now dismiss this screen
                UiApplication.getUiApplication().invokeLater(new Runnable() {
                    public void run() {
                        UiApplication.getUiApplication().popScreen(thisScreen);
                    }
                });
            }
        };
        threadToRun.start();
    }
}

 

2) RSSHandler - auxiliary class for parsing

public class RSSHandler extends DefaultHandler {
    boolean isItem = false;
    
    boolean isTitle = false;
    boolean isLink = false;
    boolean isDescription = false;
    boolean isPubDate = false;
    boolean isGuid = false;
    
    public String[] title = new String[] {};
    public String[] link = new String[] {};
    public String[] description = new String[] {};
    public String[] pubDate = new String[] {};
    public String[] guid = new String[] {};
    String value = "";

    public void startElement(String uri, String localName, String name, 
    		Attributes attributes) throws SAXException {
        if (!isItem) {
            if (name.equalsIgnoreCase("item"))
                isItem = true;
        } else {
            if (name.equalsIgnoreCase("title"))
                isTitle = true;
            if (name.equalsIgnoreCase("link"))
                isLink = true;
            if (name.equalsIgnoreCase("description"))
            	isDescription = true;
            if (name.equalsIgnoreCase("pubDate"))
                isPubDate = true;
            if (name.equalsIgnoreCase("guid"))
                isGuid = true;
        }
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        if (isTitle || isLink || isDescription || isPubDate || isGuid)
            value = value.concat(new String(ch, start, length));
    }

    public void endElement(String uri, String localName, String name)
            throws SAXException {
        if (isItem && name.equalsIgnoreCase("item"))
            isItem = false;
        if (isTitle && name.equalsIgnoreCase("title")) {
        	isTitle = false;
            Arrays.add(title, value);
            value = "";
        }
        if (isLink && name.equalsIgnoreCase("link")) {
        	isLink = false;
            Arrays.add(link, value);
            value = "";
        }
        if (isDescription && name.equalsIgnoreCase("description")) {
        	isDescription = false;
            Arrays.add(description, value);
            value = "";
        }
        if (isPubDate && name.equalsIgnoreCase("pubDate")) {
        	isPubDate = false;
            Arrays.add(pubDate, value);
            value = "";
        }        
        if (isGuid && name.equalsIgnoreCase("guid")) {
        	isGuid = false;
            Arrays.add(guid, value);
            value = "";
        }
    }
}

 

3) CaptionScreen (screen with BrowserField in which I need to show result of XML parsing)

public class CaptionScreen extends MyMainScreen
{    
    private BrowserField _browserField;
    
	public CaptionScreen(Application app, String section)
	{	 
		 //....	
		 GetArticles getArticles = new GetArticles("http://" + _urlWithArticles, _browserField); 
		 WaitScreen.showScreenAndWait(getArticles, "LOADING");
	}
	
    static class GetArticles implements Runnable {
    	String _url = null;
        BrowserField _resultBrowser;
    	
        public GetArticles(String urlToGet, BrowserField resultBrowser) {
            this._url = urlToGet;
            this._resultBrowser = resultBrowser;
        }
		
        public void run() { 
        	// Try to download new articles and parse the answer
            HttpConnection httpConn = null;
            InputStream is = null;
            RSSHandler rssHandler = new RSSHandler();
            
            try {
                httpConn = GetConnection(_url);
                
                is = httpConn.openInputStream();
                try {
                	SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
                	parser.parse(is, rssHandler);
                }                
                catch (ParserConfigurationException e) {
                	e.printStackTrace();
                }
                catch (SAXException e) {
                	e.printStackTrace();
                }
                catch (IOException e) {
                	e.printStackTrace();
                }
            } catch (IOException ioe) {
            } catch (Exception e) {
            } finally {
                try {
                    if ( httpConn != null ) {
                        httpConn.close();
                    }
                } catch (Exception e) {
                }
                httpConn = null;
            }
 
            final String htmlArticles = generateHtml(rssHandler); 
            UiApplication.getUiApplication().invokeLater(new Runnable() {
                public void run() {
                	_resultBrowser.displayContent(htmlArticles, "");
                }
            });
        }        
		
        // Method for html generation to showing in BrowserField
        private String generateHtml(RSSHandler rssHandler) {
			String result = "";
        	if(rssHandler == null) {
        		return result;
        	}
			result += "<HTML><HEAD><TITLE>News</TITLE></HEAD><BODY>";
			
			for(int i = 0; i < rssHandler.title.length; i++) {
				result += rssHandler.title[i] + "<br>" +
				"<a href=" + rssHandler.link[i] + ">LINK</a><br>" +
				rssHandler.description[i] + "<hr>";
			}
			
			result += "</BODY></HTML>";
			return result;
		}

		private HttpConnection GetConnection(String _url) throws IOException
        {
    		if (DeviceInfo.isSimulator())
        	{
        		_url = _url + ";deviceSide=true";
        	}
    		MyConnFact _myConnFact = new MyConnFact();
    		HttpConnection _httpConn = null;
    		
    		ConnectionDescriptor _connDesc = _myConnFact.getConnection(_url);
    		if (_connDesc != null) {
    			_httpConn = (HttpConnection)_connDesc.getConnection();
    		}
            
            return _httpConn;
        }
    }
}

 

It's working fine (showing WaitScreeen, download data), but any non-English characters is being showed as '????'
I've found some threads with same problem (especially this one

http://supportforums.blackberry.com/t5/Java-Development/How-to-show-other-Languages-in-BrowserField/...

and this one

http://supportforums.blackberry.com/t5/Java-Development/BrowserField-can-not-display-utf-8-character...

but I can't understand, how and where should I implement HttpConnection in my code.
Please, give me advise or say, how I've to modify my code to solve this issue?

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: BrowserField Encoding problem

Contributor
Posts: 34
Registered: ‎10-19-2011
My Device: 9800
My Carrier: sim free

Re: BrowserField Encoding problem

Thanks, Peter, for your reply!
I've modified my code to:

            final String htmlArticles = generateHtml(rssHandler);
			try {
				final byte[] data = htmlArticles.getBytes("utf-8");
				UiApplication.getUiApplication().invokeLater(new Runnable() {
                public void run() {
                	//_resultBrowser.displayContent(htmlArticles, "");
                	_resultBrowser.displayContent(data, "", "");
                	}
                });
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }        
        // Method for html generation
        private String generateHtml(RSSHandler rssHandler) {
			String result = "";
        	if(rssHandler == null) {
        		return result;
        	}
			result += "<HTML><HEAD><TITLE>News</TITLE></HEAD><BODY>";
			
			for(int i = 0; i < rssHandler.title.length; i++) {
				result += rssHandler.title[i] + "<br>" +
				"<a href=" + rssHandler.link[i] + ">LINK</a><br>" +
				rssHandler.description[i] + "<hr>";
			}
			
			result += "</BODY></HTML>";
			return result;
		}

 and now I can change encoding, when I'm converting String to Byte array in this string:

final byte[] data = htmlArticles.getBytes("utf-8");

When I set getBytes("utf-8") there is no change. When I set different encoding, characters are changing, but I still can't find correct encoding.

How I can check right encoding?

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: BrowserField Encoding problem

You need to set the content type on the displayContent.  I can't find a sample quickly, but from memory I think you need to set "UTF-8" (BTW, I would always use caps for UTF-8).

 

So replace this:

_resultBrowser.displayContent(data, "", "");

with

_resultBrowser.displayContent(data, "UTF-8", "");

Contributor
Posts: 34
Registered: ‎10-19-2011
My Device: 9800
My Carrier: sim free

Re: BrowserField Encoding problem

Thank you, I'm checking it now.

Contributor
Posts: 34
Registered: ‎10-19-2011
My Device: 9800
My Carrier: sim free

Re: BrowserField Encoding problem

[ Edited ]

I was trying to do what you said, but got no success.
When I set "_resultBrowser.displayContent(data, "UTF-8", "");" there was nothing after loading, no errors, no exceptions, only empty browserField.
I've made simple example of my application with this code. Can you check it on any 6 or 7 emulator (I usually use 9810)?
This is my example:

 http://depositfiles.com/files/d73u0chxz

OR

http://www.filedropper.com/encoding_2

OR

http://www.fileserve.com/file/KrhPntZ/Encoding.zip

 

encodingErrors.png

Contributor
Posts: 34
Registered: ‎10-19-2011
My Device: 9800
My Carrier: sim free

Re: BrowserField Encoding problem

[ Edited ]

I've solved the problem! Full code:

 

final String dataString = generateHtml(rssHandler);         
try {
	final byte[] dataByteArray = dataString.getBytes("UTF-8");
       	UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
            	_resultBrowser.displayContent(dataByteArray, "text/html; charset=UTF-8", "");
            	}
            });
     } catch (UnsupportedEncodingException e) {
       		e.printStackTrace();
     }

 Tanks you, peter, for solution!

Highlighted
Trusted Contributor
Posts: 109
Registered: ‎11-15-2011
My Device: blackberry 9800
My Carrier: beginner developer

Re: BrowserField Encoding problem

I make like in the code but there are some web pages displayed white pages what should I add.???

_resultBrowser.displayContent(dataByteArray, "text/html; charset=UTF-8", "");