Monday, June 8, 2015

Read Excel From Storage And Parse

Here is complete code by which we can read and parse excel file.

package pro.kondratev.androidreadxlsx;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;


public class ReadXlsx extends Activity {

static final int BUF_SIZE = 8 * 1024;
protected EditText output;
protected String outputString;
protected Handler handler;
protected InputStream xlsxFileStream;
protected ProgressBar progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_xlsx);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Lock portrait orientation

//        readExcelFile(this, "/storage/sdcard0/Download/ExcelOrderFile.xls");
//        readExcelFile(this, "/storage/sdcard0/Download/ReligiousPack_DailyRevenueReport_June_2015.xls");
        readExcelFile(this, "/storage/sdcard0/Download/DailyReport_April_2015.xls");
       
       
    }

   
    private static void readExcelFile(Context context, String filename) {
   
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            Log.w("FileUtils", "Storage not available or read only");
            return;
        }

        try{
            // Creating Input Stream
            File file = new File(/*context.getExternalFilesDir(null),*/ filename);
            FileInputStream myInput = new FileInputStream(file);

            // Create a POIFSFileSystem object
            POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

            // Create a workbook using the File System
            HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

            // Get the first sheet from workbook
            HSSFSheet mySheet = myWorkBook.getSheetAt(1);

            /** We now need something to iterate through the cells.**/
            Iterator<Row> rowIter = mySheet.rowIterator();

            while(rowIter.hasNext()){
                HSSFRow myRow = (HSSFRow) rowIter.next();
                Iterator<Cell> cellIter = myRow.cellIterator();
                while(cellIter.hasNext()){
                    HSSFCell myCell = (HSSFCell) cellIter.next();
                    Log.w("FileUtils", "Cell Value: " +  myCell.toString());
                    Toast.makeText(context, "cell Value: " + myCell.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        }catch (Exception e){e.printStackTrace(); }

        return;
    }

    public static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    public static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }
}
   
   
Download source code here.

Reference: Googling

   


Friday, June 5, 2015

Read excel from a URL and Parse

Here is the code to read and parse excel file from url

ReadExcelFromUrlActivity.java

package com.example.readexcel;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import com.example.readexcelfromurl.R;

import android.app.Activity;
import android.widget.ArrayAdapter;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.ListView;
import android.widget.Toast;
public class ReadExcelFromUrlActivity extends Activity {
private String LOG_TAG = "ReadExcelFromUrl";


ArrayList<ShoppingCart> shoppingCartList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);

//URL path for the Excel file
String url = "http://demo.mysamplecode.com/Servlets_JSP/demoFiles/ExcelOrderFile.xls";
excelURL(url);

}

private void displayCart() {

//Array list of countries
List<String> myList = new ArrayList<String>();
for(int i = 0, l = shoppingCartList.size(); i < l; i++){
ShoppingCart shoppingCart = shoppingCartList.get(i);
String myData = shoppingCart.getItemNumber() + ": " +
shoppingCart.getDescription() + "\nPrice: $" +
shoppingCart.getPrice() + "\nQuantity: " +
shoppingCart.getQuantity();
myList.add(myData);
System.out.println("My data..................."+ myData);
}

//Display the Excel data in a ListView
// ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
// R.layout.data_list, myList);
// ListView listView = (ListView) findViewById(R.id.listView1);
// listView.setAdapter(dataAdapter);


}

public void excelURL(String url) {
Log.v(LOG_TAG, url);
new ExcelURL().execute(url);
}

private class ExcelURL extends AsyncTask<String, Void, String> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
private String content = null;
private ProgressDialog dialog = new ProgressDialog(ReadExcelFromUrlActivity.this);

protected void onPreExecute() {
dialog.setMessage("Getting your data... Please wait...");
dialog.show();
}

protected String doInBackground(String... urls) {

String URL = null;

try {

URL = urls[0];
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

HttpGet httpGet = new HttpGet(URL);
response = httpclient.execute(httpGet);

StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
parseExcel(response.getEntity().getContent());
} else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.w("HTTP2:",e );
content = e.getMessage();
cancel(true);
} catch (IOException e) {
Log.w("HTTP3:",e );
content = e.getMessage();
cancel(true);
}catch (Exception e) {
Log.w("HTTP4:",e );
content = e.getMessage();
cancel(true);
}

return content;
}

protected void onCancelled() {
dialog.dismiss();
Toast toast = Toast.makeText(ReadExcelFromUrlActivity.this,
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();

}

protected void onPostExecute(String content) {
dialog.dismiss();
displayCart();
}



private void parseExcel(InputStream fis){

shoppingCartList = new ArrayList<ShoppingCart>();

try{

// Create a workbook using the Input Stream
HSSFWorkbook myWorkBook = new HSSFWorkbook(fis);

// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);

// We now need something to iterate through the cells
Iterator<Row> rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){

HSSFRow myRow = (HSSFRow) rowIter.next();
// Skip the first 2 rows
if(myRow.getRowNum() < 2) {
continue;
}

ShoppingCart shoppingCart = new ShoppingCart();

Iterator<Cell> cellIter = myRow.cellIterator();
while(cellIter.hasNext()){

HSSFCell myCell = (HSSFCell) cellIter.next();
String cellValue = "";

// Check for cell Type
if(myCell.getCellType() == HSSFCell.CELL_TYPE_STRING){
cellValue = myCell.getStringCellValue();
}
else {
cellValue = String.valueOf(myCell.getNumericCellValue());
}

// Just some log information
Log.v(LOG_TAG, cellValue);

// Push the parsed data in the Java Object
// Check for cell index
switch (myCell.getColumnIndex()) {
case 0:
shoppingCart.setItemNumber(cellValue);
break;
case 1:
shoppingCart.setDescription(cellValue);
break;
case 2:
shoppingCart.setPrice(Double.valueOf(cellValue));
break;
case 3:
shoppingCart.setQuantity(Double.valueOf(cellValue));
break;
default:
break;
}

}

// Add object to list
shoppingCartList.add(shoppingCart);
}
}
catch (Exception e){
e.printStackTrace();
}

}

}

}


ShoppingCart.java


package com.example.readexcel;


public class ShoppingCart {

String itemNumber = null;
String description = null;
Double price = null;
Double quantity = null;

public String getItemNumber() {
 return itemNumber;
}
public void setItemNumber(String itemNumber) {
 this.itemNumber = itemNumber;
}
public String getDescription() {
 return description;
}
public void setDescription(String description) {
 this.description = description;
}
public Double getPrice() {
 return price;
}
public void setPrice(Double price) {
 this.price = price;
}
public Double getQuantity() {
 return quantity;
}
public void setQuantity(Double quantity) {
 this.quantity = quantity;
}


}

Download full code here.

Reference:
http://www.mysamplecode.com/2012/08/android-read-excel-file-from-website.html



Receive Emails by java mail API Android


We can get email through IMAP (Internet Message Access Protocol) Protocol that makes a copy of all mails from your email id and you can get mail using it. Here is a little source code by which we can get email from any gmail id.


package com.example.reademaildemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class EmailAttachmentReceiverActivity extends Activity {

Properties properties = null;
   private Session session = null;
   private Store store = null;
   private Folder inbox = null;
   private String userName = "";// provide user name
   private String password = "";// provide password
   String downloadDirectory = Environment.getExternalStorageState() + "/downloads/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_email_attachment_receiver);
readMails();

/* Properties props = new Properties();
   //IMAPS protocol
   props.setProperty("mail.store.protocol", "imaps");
   //Set host address
   props.setProperty("mail.imaps.host", "imap.gmail.com");
   //Set specified port
   props.setProperty("mail.imaps.port", "993");
   //Using SSL
   props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
   props.setProperty("mail.imaps.socketFactory.fallback", "false");
   //Setting IMAP session
   Session imapSession = Session.getInstance(props);
   
try {
Store store = imapSession.getStore("imaps");
//Connect to server by sending username and password.
//Example mailServer = imap.gmail.com, username = abc, password = abc
store.connect("imap.gmail.com", "email", "pass");     // put email and password here.........
//Get all mails in Inbox Forlder
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
//Return result to array of message
Message[] result = inbox.getMessages();
Log.d("EMAILBYSHIVANG","here...");
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getSubject());
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getMessageNumber());
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getDescription());
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getReceivedDate());
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getFileName());
Log.d("EMAILBYSHIVANG", "result.................."+result[result.length-1].getSubject());
Multipart mp = (Multipart) result[0].getContent();
            BodyPart bp = mp.getBodyPart(0);
            System.out.println("SENT DATE:" + result[0].getSentDate());
            System.out.println("SUBJECT:" + result[0].getSubject());
            System.out.println("CONTENT:" + bp.getContent());
} catch (Exception e) {
Log.d("EMAILBYSHIVANG","Exception........................");
e.printStackTrace();
}
*/ }
public void readMails() {
        properties = new Properties();
        properties.setProperty("mail.host", "imap.gmail.com");
        properties.setProperty("mail.port", "995");
        properties.setProperty("mail.transport.protocol", "imaps");
        session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(userName, password);
                    }
                });
        try {
            store = session.getStore("imaps");
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
//            Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
            Message messages[] = inbox.getMessages();

            System.out.println("Shivang........Number of mails = ......................" + messages.length);
            for (int i = 0; i < messages.length; i++) {
                Message message = messages[i];
                Address[] from = message.getFrom();
                System.out.println("Shivang-------------------------------");
                System.out.println("Date : " + message.getSentDate());
                System.out.println("From : " + from[0]);
                System.out.println("Subject: " + message.getSubject());
                System.out.println("Content :");
                processMessageBody(message);
                System.out.println("--------------------------------");
            }
            inbox.close(true);
            store.close();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
}

    public void processMessageBody(Message message) {
        try {
            Object content = message.getContent();
            // check for string
            // then check for multipart
            if (content instanceof String) {
                System.out.println("String Content:....................."+content);
            } else if (content instanceof Multipart) {
            System.out.println("Multipart content...........................");
                Multipart multiPart = (Multipart) content;
                procesMultiPart(multiPart);
            } else if (content instanceof InputStream) {
            System.out.println("Input stream.................................");
                InputStream inStream = (InputStream) content;
                int ch;
                while ((ch = inStream.read()) != -1) {
                    System.out.write(ch);
          
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

 /*   public void procesMultiPart(Multipart content) {

        try {
            int multiPartCount = content.getCount();
            for (int i = 0; i < multiPartCount; i++) {
                BodyPart bodyPart = content.getBodyPart(i);
                Object o;

                o = bodyPart.getContent();
                if (o instanceof String) {
                    System.out.println(o);
                } else if (o instanceof Multipart) {
                    procesMultiPart((Multipart) o);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }*/
    
    public void procesMultiPart(Multipart content) {
   
    System.out.println("Here to get attchment,.................................");
        try {
            for (int i = 0; i < content.getCount(); i++) {
                BodyPart bodyPart = content.getBodyPart(i);
                Object o;
                o = bodyPart.getContent();
                if (o instanceof String) {
                    System.out.println("Text............................... = " + o);
                } else if (null != bodyPart.getDisposition()
                        && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                   
                    System.out.println("Saving Attached Doc.............................................");

               
                String fileName = bodyPart.getFileName();
                    System.out.println("fileName = " + fileName);
                    InputStream inStream = bodyPart.getInputStream();
                    
                    
                    System.out.println("Saving Attached Doc.............................................");
                    
//                    String root = getFilesDir().getAbsolutePath();
            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root + "/EmailTestFolder");    
            myDir.mkdirs();
           
            File file = new File (myDir, fileName);
            if (file.exists ()) file.delete (); 
            /*try {
            FileOutputStream out = new FileOutputStream(file);
//             bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            } catch (Exception e) {
            e.printStackTrace();
//             CommonsObjects.logger.log("Exception when save Bitmap to Sd Card", e);
            }
            }*/
                    
                FileOutputStream outStream = new FileOutputStream(file);
                    
//                    FileOutputStream outStream = new FileOutputStream(new File(
//                            downloadDirectory + fileName));
                    byte[] tempBuffer = new byte[4096];// 4 KB
                    int numRead;
                    while ((numRead = inStream.read(tempBuffer)) != -1) {
                        outStream.write(tempBuffer);
                    }
                    inStream.close();
                    outStream.close();
                }
                // else?
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    
    
    public void closeSession() {
        if (null != inbox && null != store) {
            try {
                inbox.close(true);
                store.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
    public void deleteMessage(Message message) {
        try {
            message.setFlag(Flags.Flag.DELETED, true);
            System.out.println("deleted mail");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Android Permissions Required:

<uses-permission android:name="com.google.android.gm.permission.READ_GMAIL"/>
<uses-permission android:name="com.google.android.gm.permission.WRITE_GMAIL"/>
<uses-permission android:name="com.google.android.gm.permission.MailProvider"/>
<uses-permission android:name="android.permission.INTERNET"/>
  
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


Download complete demo project from here.

Reference: Googling.