Some Useful Android Libraries


List of open source Libraries


This article is going to describe some popular and useful android open source libraries. The use of these open source libraries makes android development fast, flexible and robust.

Android Annotation framework

 

AndroidAnnotations is an Open Source framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what's really important. By simplifying your code, it facilitates its maintenance.

 



Dagger

 

A fast dependency injector framework for Android and Java

iText 

 

An open source java and android library used for PDF generation. A sample demo with source code is posted here


AChartEngine – Charting API

As AChartEngine is a charting library for Android applications. It currently supports the following chart types: There are more charting APIs as well but the most flexible and open source API that I found is AChartEngine.
  • Line chart
  • Area chart
  • Scatter chart
  • Time chart
  • Bar chart
  • Pie chart
  • Bubble chart
  • Doughnut chart
  • Range (high-low) bar chart
  • Dial chart / gauge
  • Combined (any combination of line, cubic line, scatter, bar, range bar, bubble) chart
  • Cubic line chart
A sample demo with source code is posted here


Android Scripting

 

Scripting Layer for Android (SL4A) allows scripting language to be executed on android. Scripts can be run interactively in a terminal, in the background, or via Locale. Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell are currently supported.



GSON


Gson is a Java library used for serializing and deserializing Java objects from and into JSON. A task you will frequently need to do if you communicate with APIs. We mostly use JSON because it’s lightweight and much simpler than XML.

// Serialize 
String userJSON = new Gson().toJson(user);

// Deserialize
User user = new Gson().fromJson(userJSON, User.class);

It also plays nice with the next library:



RETROFIT


From their site: "Retrofit turns your REST API into a Java interface.” It’s an elegant solution for organizing API calls in a project. The request method and relative URL are added with an annotation, which makes code clean and simple.

With annotations, you can easily add a request body, manipulate the URL or headers and add query parameters.


Adding a return type to a method will make it synchronous, while adding a Callback will allow it to finish asynchronously with success or failure.



Conclusion



As we can see from the examples above, most of the new Android libraries and tools available are indicating a need for lightweight and simpler libraries that work in unstable environments which everyone can use. There is also a little confusion between Android & Java, where things are ported from Android to Java and vice versa but if you can write something that works on both, then why not do it.

 



 

Generating complex type PDF in JAVA using iText

Last days I was searching for generating a PDF in android using iText, I found some of posts but all these posts were containing some sort of basic hello PDF reports and my requirements was to generate a complex type PDF for client reporting purpose.

So I came across the solution and want to share the source code and stuff for audience time saving purpose. Hope this helps some body :).

Note: This source code works on any java platform and not specific to Android only.



The PDF contains almost all components such as drawing tables, images, lines, different types alignments, strike through text, underline texts, different fonts and page division etc. Looks like:

PDF using iText
You can customize the below code according to your own needs.

GeneratePDF.java



public class GeneratePDF {
 
    public static String FILE = "D:/" + getUniqueFileName();
    private static Font largeBold = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
    private static Font mediumNormal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
    private static Font smallNormal = new Font(Font.FontFamily.TIMES_ROMAN, 9, Font.NORMAL);
    private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 9, Font.BOLD);
 
    static PdfWriter writer;
    static Document document;
    static PdfPCell table_cell;

    public GeneratePDF(){
        try {
            Log.v("GeneratePDF", "GeneratePDF Started...");
            document = new Document(PageSize.A4, 60, 60, 60, 60);
            writer = PdfWriter.getInstance(document, new FileOutputStream(FILE));
            document.open();
         
            addMetaData(document);       
            addTitlePage(document);
         
            document.close();
            Log.v("GeneratePDF Called", "GeneratePDF Ended...");

        } catch (Exception e) {
            e.printStackTrace();
        }
   }
 
    private static void addMetaData(Document document) {
        document.addTitle("Android");
        document.addSubject("Loan Calculator");
        document.addKeywords("Java, Android");
        document.addAuthor("Naeem Shah");
        document.addCreator("Naeem Shah");
    }

    private static void addTitlePage(Document document) throws DocumentException, IOException {
        Paragraph preface = new Paragraph();
        // Lets write a big header
        preface.add(new Paragraph("Your Main Title Here.", largeBold));
     
        // Add empty line
        addEmptyLine(preface, 4);
     
        // Will create: Report generated by: _name, _date
        //preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), smallNormal));
     
        document.add(preface);
     
        String imagePath = "D:/logosmall.png";

        Image image = null;
        try {
            image = Image.getInstance(imagePath);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
     
        image.setAbsolutePosition(450f, 710f);
        document.add(image);
     
        createTable1();
     
        Paragraph volkswagen = new Paragraph();
        volkswagen.add(new Paragraph("naeemgik.blogspot.com", largeBold));
        addEmptyLine(volkswagen, 2);
        document.add(volkswagen);
     
            
        PdfContentByte cb = writer.getDirectContent();
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 24);
        cb.moveTo(60, 580);
        cb.lineTo(400, 580);
        cb.setLineWidth(0.80f);
        cb.stroke();
     
        Paragraph pricePara = new Paragraph();
     
        PdfPTable priceTable = new PdfPTable(3);
        priceTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        priceTable.setWidthPercentage(70);
        priceTable.setHorizontalAlignment(Element.ALIGN_LEFT);
     
        priceTable.addCell(new Paragraph("PRICE", mediumNormal));
        priceTable.addCell(new Paragraph("50000" + " AZN", mediumNormal));
        priceTable.addCell(new Paragraph("55000" + " AZN", new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.STRIKETHRU)));
     
        priceTable.addCell(new Paragraph("DISCOUNT", mediumNormal));
        priceTable.addCell(new Paragraph("5", mediumNormal));
        priceTable.addCell("");
      
        pricePara.setAlignment(Element.ALIGN_LEFT);
        pricePara.setIndentationLeft(0);
        pricePara.add(priceTable);
        addEmptyLine(pricePara, 2);
        document.add(pricePara);
     
        PdfContentByte cb1 = writer.getDirectContent();
        cb1.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 30);
        cb1.moveTo(60, 515);
        cb1.lineTo(400, 515);
        cb1.setLineWidth(1.5f);
        cb1.stroke();
     
        Paragraph loanPara = new Paragraph();
     
        PdfPTable  loanTable = new PdfPTable(3);
        loanTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        loanTable.setWidthPercentage(70);
        loanTable.setHorizontalAlignment(Element.ALIGN_LEFT);
     
        loanTable.addCell(new Paragraph("LOAN_AMOUNT", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("300" + " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell(new Paragraph("AMOUNT_OF_INTEREST", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("300"+ " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell(new Paragraph("DURATION", mediumNormal));
        table_cell = new PdfPCell(new Paragraph(ShowCalculation.calcMonths + " Months", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell("\n");
        table_cell = new PdfPCell(new Paragraph("\n", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell(new Paragraph("MONTHLY_FEE", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("20"+ " AZN / " + ShowCalculation.lastMonthFee + " AZN (last Month)", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell(new Paragraph("INIT_PAYMENT", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("50"+ " AZN",  new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.UNDERLINE)));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanPara.setAlignment(Element.ALIGN_LEFT);
        loanPara.add(loanTable);
        addEmptyLine(loanPara, 2);
        document.add(loanPara);
     
        PdfContentByte cb2 = writer.getDirectContent();
        cb2.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 20);
        cb2.moveTo(60, 385);
        cb2.lineTo(400, 385);
        cb2.setLineWidth(0.80f);
        cb2.stroke();
     
        Paragraph detailPara = new Paragraph();
     
        PdfPTable  detailTable = new PdfPTable(3);
        detailTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        detailTable.setWidthPercentage(70);
        detailTable.setHorizontalAlignment(Element.ALIGN_LEFT);
     
        detailTable.addCell(new Paragraph("FIRST_INSTALLMENT", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("20"+ " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
     
        detailTable.addCell(new Paragraph("CMPR_INSURANCE", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("10" + " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
     
        detailTable.addCell(new Paragraph("BANK_FEE", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("10" + " AZN / ", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
     
        detailTable.addCell(new Paragraph("CMP_INSURANCE", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("500" + " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
     
        detailTable.addCell(new Paragraph("DYP_REG", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("500" + " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
      
        detailPara.setAlignment(Element.ALIGN_LEFT);
        detailPara.add(detailTable);
        addEmptyLine(detailPara, 2);
        document.add(detailPara);
     
        PdfContentByte cb3 = writer.getDirectContent();
        cb3.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 10);
        cb3.moveTo(60, 270);
        cb3.lineTo(400, 270);
        cb3.setLineWidth(0.25f);
        cb3.stroke();
     
        Paragraph gracePeriodPara = new Paragraph();
     
        PdfPTable  gracePeriodTable = new PdfPTable(3);
        gracePeriodTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        gracePeriodTable.setWidthPercentage(70);
        gracePeriodTable.setHorizontalAlignment(Element.ALIGN_LEFT);
     
        gracePeriodTable.addCell(new Paragraph("GRACE_PERIOD", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("0 Months", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        gracePeriodTable.addCell(table_cell);
     
        gracePeriodPara.setAlignment(Element.ALIGN_LEFT);
        gracePeriodPara.add(gracePeriodTable);
        addEmptyLine(gracePeriodPara, 1);
        document.add(gracePeriodPara);
     
    }

    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }
 
    private static String getUniqueFileName() {
         String uniqueFileName = "";
         Date date = new Date();
         uniqueFileName = date.toString();
         uniqueFileName = uniqueFileName.replace(':', ' ');
         uniqueFileName = uniqueFileName.replace('+', ' ');
         uniqueFileName += " Report";
      
         return uniqueFileName + ".pdf";
    }
 
    private static void createTable1() throws DocumentException{
       Paragraph personalInfo = new Paragraph();
     
        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(65);
        table.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
     
        table.addCell(new Paragraph(getCurrentDate(), smallBold));
        table.addCell(new Paragraph("Date", smallBold));
     
        table.addCell(new Paragraph("PHONE_NUMBER", smallNormal));
        table.addCell(new Paragraph("Phone", smallNormal));
     
        table.addCell(new Paragraph("FAX_NUMBER", smallNormal));
        table.addCell(new Paragraph("Fax", smallNormal));
     
        table.addCell(new Paragraph("EMAIL", smallNormal));
        table.addCell(new Paragraph("E-Mail", smallNormal));
     
        personalInfo.setAlignment(Element.ALIGN_RIGHT);
        personalInfo.setIndentationLeft(200);
        personalInfo.add(table);
        document.add(personalInfo);
    }
   
    public static void main(String [] args){
       GeneratePDF generatePDF = new GeneratePDF();
    }
   
     // used to get current date of the device
       public static String getCurrentDate() {
              int year;
              int month;
              int day;
             
              String currentDate = "";
              Date d1 = null;
              final Calendar c = Calendar.getInstance();
              SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

              year = c.get(Calendar.YEAR);
              month = c.get(Calendar.MONTH) + 1;
              day = c.get(Calendar.DAY_OF_MONTH);
              currentDate = "" + year + "-" + month + "-" + day + "";
              try {
                     d1 = dateFormat.parse(currentDate);
              } catch (ParseException e) {
                     e.printStackTrace();
              }

              return dateFormat.format(d1);
        }
}


Note(s):

This source code uses iText as external API so import itextpdf-5.2.1.jar