Header

Saturday, October 11, 2014

Creating PDF file in Android Application

Hi guys,
      At the end of this session you will have a clear idea about creating PDF's in android Application.Sometimes, you need to create certain applications where in you want to output the details in the form of a PDF file so that it could printed or used in some other way. Download the complete source code here.

Step 1:-
  Create a New Android Project as "PDFCreation".

Step 2:-
  In order to generate PDF we are going to use an external library called itext which is used for PDF creation.You can download the latest version of iText library from here.

Step 3:-
  After downloading itext library, copy the jar file. Now go to Eclipse, open your project and paste the iText library file under the "libs" folder .
  • Then Right click your project 
  • Click Build path, 
  • Configure Build Path.

A dialog box will appear as shown below:-


  • Click Libraries Tab 
  • Add JARs 
  • Will show dialog which list all your projects as shown below:-


  • Select your PDF creation project 
  • Go to the libs folder 
  • Select the iText jar library 
  • Then click Ok.

Step 4:-
Open your layout xml file from res/layout folder.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/createBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="145dp"
        android:text="Create Pdf" />

</RelativeLayout>


Step 5:-
Open your java file from src folder.
In my project I have created as "CreatePdf.java".

package com.ruleandroid.pdfcreation;

import java.io.FileNotFoundException;
importproject 
Click Build path, 
Configure Build Path. java.io.FileOutputStream;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CreatePdf extends ActionBarActivity implements OnClickListener {

private static String FILE = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/filename.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
Button createPdf;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_pdf);
createPdf = (Button) findViewById(R.id.createBtn);
createPdf.setOnClickListener(this);

}

private void createPdf() {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addContent(document);
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}

private static void addContent(Document document) throws DocumentException {

Anchor anchor = new Anchor("Anchor", catFont);
anchor.setName("Hello PDF");

// Second parameter is the number of the chapter
Chapter catPart = new Chapter(0);

Paragraph subPara = new Paragraph("Android PDF Created", subFont);
addEmptyLine(subPara, 1);
Section subCatPart = catPart.addSection(subPara);

Paragraph paragraph = new Paragraph();
addEmptyLine(paragraph, 5);
// subCatPart.add(paragraph);
// Add a table
createTable(subCatPart);
// Now add all this to the document
document.add(catPart);

}
private static void createTable(Section subCatPart)
throws BadElementException {

PdfPTable table = new PdfPTable(4);
PdfPCell c1 = new PdfPCell(new Phrase("Cell 1"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);

c1 = new PdfPCell(new Phrase("Cell 2"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);

c1 = new PdfPCell(new Phrase("Cell 3"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);

c1 = new PdfPCell(new Phrase("Cell 4"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
subCatPart.add(table);
}
// method to add empty line
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_pdf, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.createBtn:

createPdf();
break;

default:
break;
}
}
}


Step 6:-
Add permission in AndroidManifest file as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 7:-
Connect your real device to the development environment and run the application.

Step 8 :-
Once your application has launched click the create PDF button.After clicking, go to the sdcard directory your pdf will be created.

Wednesday, October 8, 2014

Installing and Configuring Eclipse:

To install Eclipse, you need to extract the contents of the Eclipse .zip file to the location of your choice. For this example, I’ll be using C:\ProgramFiles\Eclipse.

To install Eclipse, follow these steps:

1.Double-click the shortcut that you just created to run Eclipse:
      If you’re running a recent version of Windows, the first time you run Eclipse, a Security Warning dialog box may appear. This dialog box tells you that the publisher has not been verified and asks       whether you still want to run the software. Clear the Always Ask Before Opening This File check box, and click the Run button.

2. Set your workspace:
     When Eclipse starts, the first thing you see is the Workspace Launcher dialog box, as shown in Figure. Here, you can modify your workspace if you want, but for this book, I’m sticking with the default: c:\users\<username>\workspace
Leave the Use This as the Default and Do Not Ask Again check box deselected, and click the OK button.

3.Configuring Eclipse:
     Android Development Tools (ADT) adds functionality to Eclipse to do a lot of the work for you. The ADT allows you to create new Android projects easily;it creates all the necessary base files so that you can start coding your application quickly. It also allows you to debug your application using the Android SDK tools. Finally, it allows you to export a signed application file, known as an Android Package (APK), right from Eclipse, eliminating the need for some command-line tools.

4. Choose Windows -- Help -- Install New Software:
The Install window pops up. This window allows you to install new plug-ins in Eclipse.

5. Click the Add button to add a new site that will display the Add Repository window:
      Sites are the Web addresses where the software is hosted on the Internet. Adding a site to Eclipse makes it easier for you to update the software when a new version is released.

6. Type a name in the Name field:
     I recommend using Android ADT, but it can be anything you choose.

7. Type https://dl-ssl.google.com/android/eclipse/ in the Location field.

8. Click the OK button:
     Android ADT is selected in the Work With drop-down menu, and the available options are displayed in the Name and Version window of the Install Details dialog box.

9. In the Install dialog box, select the check box next to Developer Tools,and click the Next button.

10. Click the Next button to review the software licenses.

11. Click the Finish button.

12. When you’re prompted to do so, click the Restart Now button to restart Eclipse.
      The ADT plug-in is installed.


Setting the location of the SDK

Follow these steps:
1. Choose Window -- Preferences.
2. Select Android in the left pane.
3. Set the SDK Location to C:\android\android-sdk-windows.
4. Click OK

Introduction to JSON


JSON stands for JavaScript Object Notation, is a simple and easy to read, write, store and exchange data format. It has become popular worldwide as it is being used in  infinite projects. JSON is a best alternative solution for XML.

What is JSON
  • JSON stands for JavaScript Object Notation
  • JSON is lightweight text-data interchange format
  • JSON is platform/language independent
  • JSON is “self-describing” and “self understandable”

Extension
   JSON filename extension is .json

MIME type
   JSON Internet Media type is application/json

Programming language support
  JSON is language independent and it is supported by most of all the programming languages:

Uses of JSON
  • JSON is used when writing JavaScript based application which includes browser and websites.
  • JSON format is used for serializing & transmitting structured data over network connection.
  • JSON is primarily used to transmit data between server and web application.
  • Web Services and API.s use JSON format to provide public data. Eg. Twitter
  • JSON can be used with modern programming languages like Java, C# etc.,

JSON Syntax

Let’s discuss about JSON basic sytax. JSON syntax is primarily considered as a subset of JavaScript syntax.

JSON Syntax Rules

JSON syntax is as follows:
  • Data is in name/value pairs.
  • Data is separated by commas.
  • Curly braces hold objects
  • Square brackets hold arrays

Let’s discuss about JSON basic sytax. JSON syntax is primarily considered as a subset of JavaScript syntax.

JSON Syntax Rules

JSON syntax is as follows:
  • Data is in name/value pairs.
  • Data is separated by commas.
  • Curly braces hold objects
  • Square brackets hold arrays
JSON Data (Name/Value pairs)

JSON data is specified as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
“Language” : “JSON”
This is human readable and simply understood as:
Language = “JSON”

JSON Objects (Name/Value pairs)

JSON objects are mentioned inside curly brackets,
Objects can contain multiple name/values pairs or even array:
“Language”:”JSON” , “Author”:”Douglas Crockford”

JSON Arrays

JSON arrays are written inside square brackets.

An array can contain multiple objects:
{
“Languages”: [
{ "Language":"C" , "Creator":"Dennis Ritchie" },
{ "Language":"C++" , "Creator":"Bjarne Stroustrup" },
{ "Language":"Java" , "Creator":"James Gosling" }
]
}


Quick recap
  • Data is represented in name/value pairs
  • Curly braces hold objects and each name is followed by ‘:’(colon). The name/value pairs are separated by , (comma).
  • Square brackets hold arrays and values are separated by ,(comma).

JSON Datatypes
JSON supports following datatypes:

Number
String
Boolean
Array
Object
null

Number
It can be a decimal integer or decimal floating point number. Octal and hexadecimal formats are not supported.
Syntax
var json_num_obj = { “string” : number_value1, string : number_value2…….}
Usage
var json_student= { “maths”: 80, “science” : 87, “social” :78}

String
It is a sequence of zero or more characters put inside as double quotes.
Syntax
var json_str_obj = { “string” : “str_value1″, “string” : “str_value2″…….}
Usage
var json_str_fullname = { “firstName”:”Programmer” , “lastName”:”Guru” }

Boolean
It includes true or false values.
Syntax
var json_bool_obj = { “string”: true/false…….}
Usage
var json_stud_rank = { “distinction”:true , “class topper”:true }

Array

  • It is an ordered collection of values.
  • The values are enclosed square brackets which means that array begins with ‘[' and ends with ']‘
  • The values are separated by ,(comma).
  • Array index starts from 0.

Syntax
var json_bool_obj = { “string1″: [
{"string2": "string":"value"},
{"string2": "string":"value"},
{"string2": "string":"value"},
]
}
Usage
var json_lang_array =
{ “languages”: [
{ "language":"C" , "Creator":"Dennis Ritchie" },
{ "language":"C++" , "Creator":"Bjarne Stroustrup" },
{ "language":"Java" , "Creator":"James Gosling" }
]
}

Object

  • It is an unordered set of name/value pairs.
  • Object are enclosed in curly braces like it starts with ‘{‘ and ends with ‘}’.
  • Each name is followed by ‘:’(colon) and the name/value pairs are separated by , (comma). Make sure both name and value are enclosed within double quotes.
  • The keys must be strings and should be different from each other.

Syntax
var json_bool_obj = { “string1″: “value”.”string2″:”value”……..}
Usage
var json_obj = { “Language”:”JSON” , “Author”:”Douglas Crockford”}

Null
It means empty type.
Syntax
var json_null_obj = { “Language”:null }
Usage
var i = null;
if(i==1)
{
document.write(“<h1>value is 1</h1>”);
}
else
{
document.write(“<h1>value is null</h1>”);
}


JSON vs XML

Similarities between JSON and XML:

  • JSON is plain text like XML
  • JSON is “self-describing”(human readable) and “self-understandable” as XML
  • JSON is hierarchical (values within values)
  • JSON can be parsed by JavaScript
  • JSON data can be transported using AJAX


Differences between JSON and XML:

  • No end tag like XML
  • Shorter than XML
  • Quicker to read and write when compare to XML
  • Can be parsed using built-in JavaScript functions like eval() and parse()
  • Uses arrays – Efficient for handling huge data
  • No reserved words


Why JSON?
JSON is faster and easier than XML when you are using it in AJAX web applications:
Steps involved in exchanging data from web server to browser involves:

Using XML

  • Fetch an XML document from web server
  • Use the XML DOM to loop through the document
  • Extract values and store in variables
  • It also involves type conversions

Using JSON
Fetch a JSON string
Parse the JSON string using eval() or parse() javascript functions

JSON Parsing
JSON string can be parsed using following JavaScript functions:
eval()
parse()

Using eval()
The eval() function can be used to convert the well formed JavaScript Object Notation(JSON) string into an object.
Invoke eval() to convert JSON string to object
var contact= eval(“(“+’{“firstname”:”Kumar”,”surname”:”Ankit”,”phone”:["999-9999-909","999-9999-999"]}’+”)”);

Don’t forget to embed JSON string with function brackets “(” and “)”.

Get values using JSON object
alert(“Hello ” + contact.firstname + “, we will contact you at ” + contact.phone[0] + “or” + contact.phone[1]);

Using parse()
The eval() function can also be used to convert the well formed JavaScript Object Notation(JSON) string into an object.
Invoke parse() to convert JSON string to object
var contact= JSON.parse(‘{“firstname”:”Kumar”,”surname”:”Ankit”,”phone”:["999-9999-909","999-9999-999"]}’);

Get values using JSON object
alert(“Hello ” + contact.firstname + “, we will contact you at ” + contact.phone[0] + “or” + contact.phone[1]);


eval() Vs parse()

  • JSON.parse() function is not supported by all browsers since the native support for the function is missing in old browsers. Check what are all browsers support JSON.parse() from here.
  • JSON is just a subset of JavaScript. JSON.parse() just parses JSON string present in JavaScript but eval evaluates the full JavaScript language and not just the subset that’s JSON which end up in parsing function calls and other JavaScript code.
  • Time taken for parsing matters: JSON.parse() parses JSON string in quick time when compare to eval().

Tuesday, October 7, 2014

How to get source code from apk file


As we now know that apk file is just a zip file containing all program resource file, we can now get java code from apk files with ease.

Following are steps to get java code from apk files.

Step 1:Renaming .apk file


  • Rename the .apk file with the extension .zip (for example let the file be "demofile.apk" then after renaming it becomes "demofile.apk.zip")


Step 2:Getting java files from apk


  • Now extract the renamed zip file in specific folder, for example let that folder be "demofolder".
  • Now Download dex2jar from the link for windows and extract that zip file in folder "demofolder".
  • Now open command prompt and go to the folder created in previous step and type the command "dex2jar classes.dex" and press enter.This will generate "classes.dex.dex2jar" file in the same folder.
  • Now  Download java decompiler from the link and extract it and start(double click) jd-gui.exe
  • From jd-gui window browse the generated "classes.dex.dex2jar" file in demofolder, this will give all the class files by src name.
  • Now from the File menu select "save all sources" this will generate a zip file named "classes_dex2jar.src.zip" consisting of all packages and java files.
  • Extract that zip file (classes_dex2jar.src.zip) and you will get all java files of the application.
  • Above steps will generate java files but to get xml files perform following steps.


Step 3:Getting xml files from apk


  • Download apktool and apktool install from the link and extract both files and place it in the same folder (for example "demoxmlfolder").
  • Place the .apk file in same folder (i.e demoxmlfolder)
  • Now open command prompt and goto  the directory where apktool is stored (here "demoxmlfolder") and type the command "apktool if framework-res.apk" 
  • Above command should result in "Framework installed ..."
  • Now in command prompt type the command "apktool d filename.apk" (where filename is name of apk file)
  • This will generate a folder of name filename in current directory (here demoxmlfolder) where all xml files would be stored in res\layout folder.


Ask the Expert

What is the difference between Google and the Open Handset Alliance?

Google is a member of the Open Handset Alliance. Google, after purchasing the original
developer of Android, released the operating system under the Open Handset Alliance.

Is Android capable of running any Linux software?

Not necessarily. While I am sure that there will be ways to get around most any open
source system, applications need to be compiled using the Android SDK to run on
Android. The main reason for this is that Android applications execute files in a specific
format; this will be discussed in later chapters.


Welcome to Android Programming


Introduction


The Open Handset Alliance (1) released the Google Android SDK on November 12th, 2007, having announced it about a week before. The impact was unbelievable, almost every IT/programming-related news-page dumped a news-post about the SDK release – the Google Groups was overwhelmed with over 2000 Messages within the first two Days.

The idea of the Android Platform was and still is amazing and is of course attracting more and more programmers every day. Especially the open architecture based on Intents and the possibility to replace even the Home-application grant a really large amount of flexibility to the whole platform.

What is Android ? 

Android, as a system, is a Java-based operating system that runs on the Linux 2.6 kernel.
The system is very lightweight and full featured.

Android is built on the open Linux Kernel. Furthermore, it utilizes a custom virtual machine that has been designed to optimize memory and hardware resources in a mobile environment. Android will be open source; it can be liberally extended to incorporate new cutting edge technologies as they emerge. The platform will continue to evolve as the developer community works together to build innovative mobile applications.

Android applications are developed in Java. Android itself is not a language, but rather
an environment within which to run applications. As such, you can theoretically use
any distribution or integrated development environment (IDE) you have at your disposal
to begin your development. In fact, you can choose to use no IDE at all.