Tuesday, July 15, 2014

Android Downloading and Viewing a PDF File Example


This tutorial is about downloading a pdf file and viewing it using an Android APP.

In this example we will be downloading the pdf file in the location http://maven.apache.org/maven-1.x/maven.pdf

Pre-Requiste
- Basic Android Knowledge
- Basic Java Knowledge

Sample Screenshots 







MainActivity.java
package com.example.downloadread;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

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

    public void download(View v)
    {
        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}
FileDownloader.java
package com.example.downloadread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="download"
        android:onClick="download" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="38dp"
        android:text="view"
        android:onClick="view" />

</RelativeLayout>

Monday, June 30, 2014

Scrum Burn Down Chart using Microsoft Excel 2010


This tutorial is about "Scrum Burn Down Chart using Microsoft Excel 2010"

Prerequisite:

  • Agile Scrum Knowledge
  • Burn Down Charts Knowledge 
  • Basic Microsoft Excel 2010+  Knowledge

Create a new spreadsheet in the Microsoft Excel 2010+

Create a List of Task, Resource and Estimate in hours / days as per your preference


Example:
Task Name: Create User Login HTML Wireframe (Master Task 1)
Resource: Developer1
Initial Estimate: 8 hrs

The below table shows the 8 days per sprint. You can add more days per sprint as per your needs.



Create all your list of Task, Resources and Estimates. With planned burn down, how much can be completed in a day.

Every day i have 6hrs per resources, hence from the initial estimate everyday reduce 6hrs per resource on each day.



Create a total (SUM) for each from Initial estimate



With this you will get the Time Left to Do by Day.



Create new Chart ( Insert Tab --> Line --> All Chart Types)




Choose chart type as  Line with Markers



Right Click the chart and Select Data



Select Chart data range as Total of Planned and Total of Actual. Hold on ctrl key to select planned and actual rows.


Edit the Label name for Planned and Actual





The label names are modified as Planned and Actual. It is reflected int he chart.



Right Click the Chart and Move Chart



You will see the complete burn down chart in a Chart Tab.


Wednesday, May 14, 2014

Java JSON JQuery

This post is a small example web application using Java, JSON, JQuery.

JSON (JavaScript Object Notation) is now conquering the attention in the Web Applications, Mobile Applications, Big Data etc., If you don't know about JSON, properly it is about time to learn.

Example JSON:  {"name":"Book Name","author":"Book Author","publisher":"Book Publisher"}

We will be using the above JSON data in our example, it is basically key value pair. Both key value are enclosed in double quotes ".  "Key" : "Value"  separated by colon :

Subsequent key values are separated by comma , and complete data is enclosed in braces { }

Prerequisite Knowledge / Skills 
-- Java 
-- Eclipse IDE
-- Basic Javascript
-- Basic JQuery knowledge 

Development Tools Required
-- Eclipse IDE Juno / Kepler 
-- Tomcat 6.0 +

Design Concept 
BookServlet  --> Get Method will retrieve the List (ArrayList) of books  in JSON Format
BookServelt --> Post Method will add Book to the List(ArrayList)
index.jsp --> will place 2 types of request, one using get and another using post. Both request are sent to BookServlet but for different methods. 

Project Structure in Eclipse with Files 
JavaJQueryJson
--.settings
--build
--src
----com
------demo
--------json
----------Book.java (src / com / demo / json )
----------BookList.java (src / com / demo / json )
----------BookServlet.java (src / com / demo / json )
----------Status.java (src / com / demo / json )
--WebContent 
------index.jsp (WebContent )
------js
------------jquery-1.11.1.js (WebContent / js )
------META-INF
------WEB-INF
------------web.xml (WebContent / WEB-INF )
------------classes
------------lib
----------------gson-2.2.4.jar (WebContent / WEB-INF / lib )


Step 1: In your eclipse IDE create a dynamic web project


Step 2: Project name  JavaJQueryJson 

Step 3: We will  be using GSON framework Java Library

Open the URL --> Navigate to Downloads 
Step 4: Copy the jar file to the Web Project/WEB-INF/lib folder

Step 5: Create a new class


Step 6: Package name --> com.demo.json  & Name: Book


Step 7: Book.java is a POJO class with 3 attributes and getter & setter


package com.demo.json;

public class Book {
private String name;
private String author;
private String publisher;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}

}

Step 8: Create BookList Class



Step 9: BookList.java is a Singleton class to add list of Books and get list of Books



package com.demo.json;

import java.util.ArrayList;
import java.util.List;

public class BookList extends Status{
private static BookList bookListInstance = null;
private List<Book> bookList = new ArrayList<Book>();
private BookList()
{
}
public void addBook(Book book)
{
bookList.add(book);
}
public List<Book> getBooks()
{
return bookList;
}
public static BookList getInstance()
{
if(bookListInstance==null)
{
return new BookList();
}
else
{
return bookListInstance;
}
}

}

Step 10: Create new java class Status



Step 11: Status.java is a simple POJO class with getter and setter



package com.demo.json;

public class Status {
private boolean status;
private String description;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}

}

Step12: Download JQuery from http://jquery.com/

And copy the js to the folder WebContent/js



Step 13:  Create a new Java Servlet 



Step 14: Name the Servlet as BookServlet


Step 15: doGet method implementation


Step 16: doPost method implementation




Source Code:

package com.demo.json;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class BookServlet
 */
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static BookList bkList = BookList.getInstance();

/**
* @see HttpServlet#HttpServlet()
*/
public BookServlet() {
super();
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType("application/json");

Gson gson = new Gson();

try {

System.out.println("BK List: " + gson.toJson(bkList.getBooks()));

response.getOutputStream().print(gson.toJson(bkList.getBooks()));
response.getOutputStream().flush();

System.out.println("doGet Success");

} catch (Exception ex) {
ex.printStackTrace();
Status status = new Status();
status.setStatus(false);
status.setDescription(ex.getMessage());
response.getOutputStream().print(gson.toJson(status));
response.getOutputStream().flush();
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

response.setContentType("application/json");

Gson gson = new Gson();

try {
StringBuilder sb = new StringBuilder();
String s;
while ((s = request.getReader().readLine()) != null) {
sb.append(s);
}

System.out.println("JSON Data: " + sb.toString());

Book book = (Book) gson.fromJson(sb.toString(), Book.class);

Status status = new Status();
if (book.getName() != null && !book.getName().trim().equals("")) {
status.setStatus(true);
status.setDescription("success");

bkList.addBook(book);
} else {
status.setStatus(false);
status.setDescription("Book name is null or empty");
}
response.getOutputStream().print(gson.toJson(status));
response.getOutputStream().flush();

System.out.println("doPost Success");

} catch (Exception ex) {
ex.printStackTrace();
Status status = new Status();
status.setStatus(false);
status.setDescription(ex.getMessage());
response.getOutputStream().print(gson.toJson(status));
response.getOutputStream().flush();
}
}

}


Step 17: index.jsp in the WebContent Folder


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Java JQuery JSON </title>
<script src="./js/jquery-1.11.1.js"> </script>
<script>
$(document).ready(function(){
  $("button").click(function(){
   $.getJSON('http://localhost:8080/JavaJQueryJson/BookServlet', '' , function(result){
     $.each(result, function(i, field){
        $.each(field, function(key, value){ 
        $("#results").append(key +": "+ value + " &nbsp;&nbsp;&nbsp;&nbsp;");
        });
        $("#results").append(" <br/> ");      
     });
   });
  });
});
function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}
function addBooks()
{
if(isEmpty($('#bookname').val()))
{
alert("Book name cannot be null");
}else
{
var dataJson = '{"name" : "'+ $('#bookname').val()+'","author" : "'+ $('#bookname').val()+'","publisher": "'+ $('#bookname').val()+'"}';
   $.ajax({
       type: 'POST',
       url: 'http://localhost:8080/JavaJQueryJson/BookServlet',
       data: dataJson, // or JSON.stringify ({name: 'bookname'}),
       success: function(result) {  
       $.each(result, function(i, field){
           $("#status").append(i +": "+ field + " <br/> ");
       });
       },
       contentType: "application/json",
       dataType: 'json'
   });
}  
}
</script>
</head>
<body>
<input type="text" name="bookname" id="bookname" /> 
<input type="button" name="btnAdd" id="btnAdd" value="Add Books" onclick="addBooks()" />
<br></br>
<div id="status"></div>
<br></br>
<button>Get Books</button>
<div id="results"></div>
</body>
</html>

Step 18: Final Result