Thursday, July 28, 2011

Android Aync task

I am working on some android applications and thought I'd share how Async task works with a simple example.

Android applications are designed to be responsive. When unresponsive the android OS uses the tough love approach and offloads the app i.e the ANR(App not responding exception). When we do network calls off the mainthread these will block since network connections are relatively slow . To avoid this problem we will need to offload this network call to another worker thread.
This can be achieved using the AsyncTask

Methods we care about in AsyncTask
*onPreExecute()-
Runs on UI Thread before handing over to worker thread

*doInBackground()
Workhorse runs in background
*publishProgress()
inform UI about progrèss called from doInBackground()
*onProgressUpdate()
runs on UI thread and updates progressBar
*onPostExecute
runs in UI thread once worker thread is done

ProgressActivity has a button which will update a progress bar when hit.


package com.foo;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends Activity implements OnClickListener {
private ProgressBar progressBar;
private Button start;

public class BackgroundAsyncTask extends AsyncTask {

int myProgress;

@Override
protected void onPostExecute(Void result) {
Toast.makeText(ProgressBarActivity.this, "onPostExecute all done back in UI",
Toast.LENGTH_LONG).show();
}

@Override
protected void onPreExecute() {
Toast.makeText(ProgressBarActivity.this,
"preexecute -before back ground processing starts",
Toast.LENGTH_LONG).show();
myProgress = 0;
}

@Override
protected Void doInBackground(Void... params) {

while (myProgress < 100) {
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(20);
}
return null;
}

@Override
protected void onProgressUpdate(Integer... values) {

progressBar.setProgress(values[0]);// called by the publishProgress
// method to update progress bar
}

}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

start = (Button) findViewById(R.id.startprogress);
progressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
progressBar.setProgress(0);

start.setOnClickListener(this);

}

@Override
public void onClick(View v) {
new BackgroundAsyncTask().execute();

}
}

Friday, March 25, 2011

Zuccini and Potato soup

I have become a big soup freak . Its been one of the fads thats infected me for the last year
This is a really easy recipe for all you folks who arent fussed about sitting by the stove all day and comes out pretty darn nice
Take a couple of potatoes cube em
Zuccini *2 remove skin and cut coarsely
onions *1 slize
garlic *2 slice

Procedure
1)roast onions and garlic
2)put zucinni onions potatoes and garlic in some vegetable stock
3)cook till tender
4)then out comes the trustee hand blender
5)blend away add some pepper and salt
6)bring to boil
7)fry some sage with butter and add on top

serve with crusty bread

How to detect language of a document

Recently I wrote a program to detect the human language of a given text . I was asked to do this task in 24 hours .After a lil googling I finally found this paper for N-Gram-Based Text Categorization by these two guys
William B. Cavnar and John M. Trenkle from Michigan AnnHarbour
Defn Worth a read...

Firstly what is a ngram ?
An Ngram is an n character slice of a string(From the paper verbatim)
so for APPLE you will have ngrams _,A,P,L,E then _A,AP,PL,LE,_AP,PLE etc

The basic algorithim if you dont have the patience to read this paper is

1)Create a ngram based profile for a document i.e this is basically finding the frequency of occurances of all the NGrams in your language document
2)Sort this ngram based profile with the highest frequency on top this would tell you the most occuring ngrams.
3)Now if you were to find the language of origin of a document then you will need to find its profile and then sort it by highest frequency
4)Now find a minimum distance between these documents i.e if the document is like the language this should be very small so the frequency of occurance of the words/syllables in the document and language would be similar .

Thursday, August 26, 2010

raagi(Finger millet) porridge for babies

I have started ragi koozhu(porridge) for my baby.Its pretty good . Ragi is very nutritious and is very good for adults also .I found this really interesting link on Ragi's nutritive value http://vegweightlossdiets.com/ragi-nutrition/

Ragi is very high in calcium and iron . In many parts of south India babies are given ragi as a first food .Sprouted ragi powder for the baby is pretty easy to make.When stored well it keeps as well though I make it once a month .

Ragi(Finger MIllet) is available in some Indian grocers I buy it from Udaya Spices at Station Street in WentworthVille.

First wash the Ragi and immerse it in water for 2 -3 hours then allow it to sprout I put the ragi in a muslin cloth and put it into my oven (any warm place should do).It takes 7-8 hours to sprout but this will vary depending on the season.
Once its sprouted the ragi is to be dried fully .I put the ragi into my oven and put the oven on fan heat for 15-20 mins .

This porridge also uses wheat and chatni chana. I buy whole wheat grains from Udaya spices wash the whole wheat and dry it in the oven for 15-20mins .I only toast the chatni chana .

The ratio I use for this porridge is ragi:wheat:chatnichana is 2:1:1 .The porridge powder can vary slightly so I Just eyeball the ratios . Now grind the roasted ragi,wheat and chatni chana till it becomes a fine powder I then run this into a seive and then store the powder in an airtight container.

To prepare the porridge I mix one spoon of the porridge powder with water and cook it .
To this I add cooked banana or pumpkin or cooked apple ,pears etc .In India I am told that its customary to use milk to cook the porridge or if cooked in water ghee is added finally. I have refrained from doing this as of now since I would like to wait before I introduce milk to the baby.

Wednesday, August 11, 2010

reminiscing

Its been more than a year since I last blogged
A lot has changed in the last one year for one I have a baby shes now close to 4 months old
she is an Anzac baby born 25th April... Its a lot of fun looking after her I never realised how hard it really is to take care of a young baby .. Lifes changed totally.... Last year this time I was sking or actually attempting to ski the slopes of queenstown though to be fair I did more falling than sking :) Well I guess we will attempt sking again this time when baby is a couple of years old:) get up on that horse again and give it a go ...

Sunday, April 19, 2009

Personality Test

I took a personality test(MBTI) this Saturday....There are 16 personality types that humans can be slotted into .... Turns out I am a ENTJ-Extraverted iNtuitive Thinking Judging .I was very sceptical about this test and thought that all these personality tests are a bit of a crock....Now I am a convinced convert This is what the profile says in short...

ENTJ(http://www.myersbriggs.org/my-mbti-personality-type/mbti-basics/the-16-mbti-types.asp)
Frank, decisive, assume leadership readily. Quickly see illogical and inefficient procedures and policies, develop and implement comprehensive systems to solve organizational problems. Enjoy long-term planning and goal setting. Usually well informed, well read, enjoy expanding their knowledge and passing it on to others. Forceful in presenting their ideas.

 

Swig

I have recently been playing around with a new interface compiler tool called SWIG
SWIG stands for SIMPLIFIED WRAPPER AND INTERFACE GENERATOR .We are using it to rapidly generate JNI code for us so that we can use it to talk to C++ through Java. Most of the examples provided in the examples are very trivial but to do more complex things the best way would be to download the code and look through the examples. I will start now with a very simple example.....We model a book class that has a vector of chapters.

class Chapter //With copy constructor
{
private:
char *name;
public:
Chapter()
{
name = new char[20];
}
char* getName(){
return name;
}
void setName(char *nam){
strcpy(name,nam);
}};


class Book //With copy constructor
{
private:
char *name;
std::vector chapter_;
public:
void addChapter(Chapter *chap){
chapter_.push_back(chap);
}
std::vector getChapter(){return chapter_;}

Book()
{
name = new char[20];
}
};


We would talk to Book class in c++ using Java.Swig generates for us the glue code to enable us to do so .To generate the swig glue code we must first create an interface file

Step 1)

/* File : example.i */
%module testModuleAPI

%include cpointer.i
%include "arrays_java.i"
%include "std_string.i"
%include "std_vector.i"
%include "chapter.h"
%{
#include "chapter.h"

%}
namespace std
{
%template(ChapterVector) vector;
};
%include "book.h"


%{
#include "book.h"

%}



Step2) Create swig artifacts
/cygdrive/c/swig-1.3.38/preinst-swig -c++ -java -package test -outdir ./test ./test/test.i


Step 3)Compile c++ classes and create a library file
g++ -mno-cygwin -I /cygdrive/c/jdk1.6.0_12/include -I /cygdrive/c/jdk1.6.0_12/include/win32 -Wl,--add-stdcall-alias -shared -o ./test/test.dll ./test/*.cxx


Step 4)Write java class to test c++

public class RunSample {
static {
System.load("C:\\workspace\\swigSamples\\src\\test\\abc.dll");
}
public static void main(String args[]){
Chapter chap=new Chapter();
chap.setName("test");
Book book=new Book();
book.addChapter(chap);
ChapterVector vec=book.getChapter();
long val=vec.size();
System.out.println("Value "+val);
Chapter chap2=vec.get(0);
System.out.println("Name >>>>"+chap2.getName());

}
}