Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, April 8, 2011

Custom Fonts on Android

Sometimes the stock fonts on Android may not cut it when trying to create the look and feel of your app so embedding a custom typeface file will be the way to go.
First, you may need some cool fonts so I recommend you to check http://www.dafont.com and get some free fonts for you project (read the license agreement before using it in your phone).

Once you have picked your fonts you need to copy it in the assets folder in your application; I normally create a subfolder called fonts but it is not required.












Then OnCreate add the following lines of code and you are ready to go:

TextView text = (TextView)findViewById(R.id.labelTitle);
Typeface customFont = Typeface.createFromAsset(getAssets(),"font/custom.ttf");
       
text.setTypeface(customFont);

In the sample above I am setting the "labelTitle" TextView to use my custom.ttf files

Yes,  that’s all.

Thursday, March 17, 2011

Android Tip: Html.fromHtml with ImageGetter

You have an Android App that just fetched HTML content from the web to be displayed on a TextView. The first thing we do is to use Html.fromHtml()  method; however, you soon realize that this method replaces all images with generic placeholders (besides not supporting all HTML tags). The good news is that this method does support ways of handling images (and other tags but this tutorial is just for images).
Implementing a ImageGetter is straight and simple; you pass an ImageGetter object to be use to fetch the images that later will be use to fill the placeholders. In order to fetch the images the ImageGetter object must implement the getDrawable method. The getDrawable method must return the Drawable object that will fill the placeholder; but, if null is returned the generic image placeholder will be used instead (see implementation below).

SpannableStringBuilder s = (SpannableStringBuilder)Html.fromHtml(htmlContent, new ImageGetter() {
                        @Override
                        public Drawable getDrawable(String source)
                        {         
                          return null;
                        } 
                    },null);

Implementing a ImageGetter is straight and simple; you pass an ImageGetter object to be use to fetch the images. The way you fetch the images will vary depending on your application needs; so for this example I will fetch the images directly to an InputStream object (sometimes the best way could be saving them to a folder in the SD card).

Fetch Method

public InputStream imageFetch(String source)
                          throws MalformedURLException,IOException {
      URL url = new URL(source);
      Object o = url.getContent();
      InputStream content = (InputStream)o;
      // add delay here (see comment at the end)     
      return content;
}



Fully Implemented Method

String s = Html.fromHtml(htmlContent, new ImageGetter() {
            @Override
         public Drawable getDrawable(String source) {                  
            Drawable d = null;
            try {
                        InputStream src = imageFetch(source);
                        d = Drawable.createFromStream(src, "src");
                        if(d != null){
d.setBounds(0,0,d.getIntrinsicWidth(),
d.getIntrinsicHeight());
                        }
} catch (MalformedURLException e) {
                  e.printStackTrace(); 
            } catch (IOException e) {
                  e.printStackTrace();  
            }

 return d;
        }

      },null);

TextView t = (TextView)findViewById(R.id.textOutput);
t.setText(s);

One thing to consider is that big images may need more time to download so depending on the connection you app may not be able to load all images. Some people work around this by saving the images on the SD card; however, I have gotten around this issue by running this method asynchronously while putting a slight delay on the imageFetch function (right before returning the content).

Thursday, December 2, 2010

Parse an RSS feed using Java



Here is a quick example of how to parse an RSS feed in Java. It may come handy when doing Android or Web apps.
The following example is being implemented as an static method in a console application; however, for a real project you may want to create a set of classes to provide a more OO approach.

private static void Rss(String feed) throws ParserConfigurationException,IOException, SAXException{

              URL url = new URL(feed);
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc;
                    doc = db.parse(url.openStream());
                    doc.getDocumentElement().normalize();
                    NodeList itemLst = doc.getElementsByTagName("item");
                   
                    for(int i=0; i < itemLst.getLength(); i++){
                         
                          Node item = itemLst.item(i);
                          if(item.getNodeType() == Node.ELEMENT_NODE){
                                Element ielem = (Element)item;
                                NodeList title = ielem.getElementsByTagName("title");
                                NodeList link = ielem.getElementsByTagName("link");
                                NodeList description = ielem.getElementsByTagName("description"); 
                                                              
                                System.out.print(title.item(0).getChildNodes().item(0).getNodeValue());
                                System.out.print("\t\n");
                                System.out.print(link.item(0).getChildNodes().item(0).getNodeValue());
                                System.out.print("\t\n");
                                System.out.print("\t\n");
                          }
                         
                    }
              }

 }

Usage:
Rss(“http://rss.cnn.com/rss/cnn_topstories.rss“);

Output:
Clinton hits phone to patch relations    
http://rss.cnn.com/~r/rss/cnn_topstories/~3/VBH1WQQ1mAI/index.html     
     
The secret life of Julian Assange  
http://rss.cnn.com/~r/rss/cnn_topstories/~3/4gGd2WPMSaE/index.html     
     
House to vote on Bush tax cuts     
http://rss.cnn.com/~r/rss/cnn_topstories/~3/c2AgZMKetoo/index.html

Round double number to two decimal places in Java

Round a double to two decimal places in Java

 private double TwoDecimalRound(double d) {
      try{
            DecimalFormat twoDForm = new DecimalFormat("#.##");
            return Double.valueOf(twoDForm.format(d));
      }catch(NumberFormatException ex){  
            //TODO: handle error
      }
      return 0;
    }

Tuesday, November 23, 2010

Android WebView - Clear The Cache

I have been asked a couple of times how to clear the cache from a WebView on an Android application. I will briefly explain the approach I am currently using:

You need to implement two methods one to retrieve all the cache data and one to delete each directories we find  cache (technically you could do it in one method but I prefer two).

Method to delete cache file(s):


  public static boolean DeleteDirectories(File d) { 
   String[] children = d.list(); 
   for (int i = 0; i < children.length; i++) { 
   boolean success = DeleteDirectories(new File(d, children[i])); 
   if (!success) { 
    return false; 
   } 
   } 
    return d.delete(); //Delete empty directory
    


Method to retrieve all directories from cache to delete:

public static void DeleteCache(Context context) { 
     try { 
    File d = context.getCacheDir(); 
    if (d != null && d.isDirectory()) { 
    DeleteDirectories(d);  
   
     } catch (Exception e) { 
        // TODO: handle as you please 
    
     } 



I normally call these methods when the user abandons the application by overriding the onDestroy() method in my main activity.

Example:

  @Override 
    protected void onDestroy() { 
     super.onDestroy();  
   try { 
DeleteCache(this);  
   } catch (Exception e) { 
       // TODO: handle as you please
   } 
    }