Wednesday, 26 September 2012

Asynchronous tasks in Android applications


Asynchronous tasks in Android applications




When we are writing an application and we want to perform a heavy background operation we have to start a new thread that will handle this operation and then publish the results on the UI thread for further processing. Having to manipulate threads can very often lead to complex pieces of code and it is pretty easy to mess things up really fast!

Android provides a class that enables proper and easy use of the UI thread and makes our life really easy. AsychTask is a class that allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps (functions), calledonPreExecute, doInBackgroundonProgressUpdate and onPostExecute.

AsyncTask must be subclassed to be used and the subclass must override at least one method (doInBackground), and most often will override a second one ( onPostExecute). Now let's take a look at the three types used by an asynchronous task:
  1. Params: The type of the parameters sent to the task upon execution.
  2. Progress: The type of the progress units published during the background computation.
  3. Result: The type of the result of the background computation.
If a type is not used by an asynchronous task, then this type is marked as unused using the type Void. Now let's take a look at the 4 steps a task goes through when it is executed:
  1. onPreExecute: Invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground: Invoked on a background thread after onPreExecute finishes executing. This function is used to perform background operations/computations that can take a long time. In this function we can use publishProgress to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate step.
  3. onProgressUpdate: Invoked on the UI thread after a call to publishProgress.Usually it is used  to animate a progress bar.
  4.  onPostExecute: Invoked on the UI thread after doInBackground finishes executing. The result of the background computation is passed to this step as a parameter.
A task can be cancelled at any time by invoking cancel function. Below I am quoting an example of the use of AsynchTask:








package a.b;
 
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
 
public class Ayntaskdemo1Activity extends Activity {
    /** Called when the activity is first created. */
 private ProgressBar mProgressBar;
 private Button mCalculationButton;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        mCalculationButton = (Button) findViewById(R.id.calculation);
         
        mCalculationButton.setOnClickListener(new OnClickListener() {
    
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    CalculationTask task = new CalculationTask();
    task.execute();
   }
  });
    }
     
    /** Task that handles the procedure to store a route on the local database */
    private class CalculationTask extends AsyncTask<Void, Integer, Long> {
     
     @Override
     protected void onPreExecute() {
      // Initialize bar
      mProgressBar.setProgress(0);
     }
      
     @Override
     protected Long doInBackground(Void... data) {
      // Store route
      long counter = 0;
      for(int i = 1; i <= 10000000; i++) {
       counter += i;
       if(i % 100000 == 0) {
        publishProgress((int) i/100000);
       }
      }
       
      return counter;
     }
      
     @Override
     protected void onProgressUpdate(Integer... progress) {
      mProgressBar.setProgress(progress[0]);
        }
      
     @Override
     protected void onPostExecute(Long result) {
    Class gallery;
         try
         {
          gallery=Class.forName("a.b.gallery");
          Intent i=new Intent(Ayntaskdemo1Activity.this,gallery);
       //     startActivityForResult(i,PICK_EXISTING_PHOTO_RESULT_CODE);
                 startActivity(i);
         }
         catch(ClassNotFoundException e)
         {
          e.printStackTrace();
         }
      // Publish result
      Toast.makeText(getApplicationContext(), "Counter is " + result, Toast.LENGTH_LONG).show();
     }
    }
}

Tuesday, 25 September 2012

JSON parsing example 1

JSON  parsing  example 1





package a.b;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class Jsonparsedemo1Activity extends Activity {
TextView tv1,tv2;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       tv1=(TextView)findViewById(R.id.textView1);
       tv2=(TextView)findViewById(R.id.textView2);
     //  {"id":12,"name":12,"status":"ok","volumes":[{"id":17592,"name":"root","status":"ok"}]}
     
     
       final String customJSON = "{\"id\":12,\"name\":12,\"status\":\"ok\",\"volumes\":[{\"id\":17592,\"name\":\"root\",\"status\":\"ok\"}]}";     //  tv1.setText(customJSON);
       try
       {
   
      JSONObject  jobj=new JSONObject(customJSON);
      String id=jobj.getString("id");
      String myname=jobj.getString("name");
      String status1=jobj.getString("status");
      String result1="id1="+id+"\n"+"name1="+myname+"\n"+"status1"+status1;
      tv1.setText(result1);
     
     
     
      JSONArray jarray=jobj.getJSONArray("volumes");
      JSONObject myobj=jarray.getJSONObject(0);
      String  id2=myobj.getString("id");
      String myname2=myobj.getString("name");
      String status2=myobj.getString("status");
      String  result="id2="+id2+"\n"+"name2="+myname2+"\n"+"status2"+status2;
     
      tv2.setText(result);
     
       }
       catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      Toast.makeText(Jsonparsedemo1Activity.this, e.toString(), Toast.LENGTH_LONG).show();
     }
      }
    }





Friday, 7 September 2012

Android Animation Example 2

                    Android Animation Example 2



SurfaceActivity.java

package a.b;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

public class SurfaceActivity extends Activity  implements OnTouchListener {
Myview abc;
float x,y;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        abc=new Myview(this);
        abc.setOnTouchListener(this);
        setContentView(abc);
        x=0;
        y=0;
    }
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
abc.pause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
abc.resume();
}
@Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
x=event.getX();
y=event.getY();
return false;
}
public class Myview extends SurfaceView implements Runnable{
SurfaceHolder myholder;
Thread t=null ;
boolean isRunning=false;

public Myview(Context context) {
// TODO Auto-generated constructor stub
super(context);
myholder=getHolder();
}
public void pause()
{
isRunning=false;
while(true)
{
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
t=null;
}
public void resume()
{
isRunning=true;
t=new Thread(this);
t.start();
}

@Override
public void run() {
// TODO Auto-generated method stub
while(isRunning)
{
if(!myholder.getSurface().isValid())
continue;
Canvas canvas=myholder.lockCanvas();
canvas.drawRGB(02, 02, 1);
if(x !=0 && y !=0)
{
Bitmap test=BitmapFactory.decodeResource(getResources(),R.drawable.f);
canvas.drawBitmap(test,x,y,null);
}
myholder.unlockCanvasAndPost(canvas);
}
}

}

}



set theme in manifest


set theme in manifest



android:theme="@android:Style/Theme.Wallpaper.NoTitleBar"

Thursday, 6 September 2012

Introduction to Animation In Android

             Introduction to Animation In Android


AninmationdemoActivity.java



package a.b;

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

public class AninmationdemoActivity extends Activity {

Myanimation anim;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        anim=new Myanimation(this);
        setContentView(anim);
    }
}




Myanimation .java


package a.b;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;

public class Myanimation extends View {
      Bitmap img,img1,img2,img3;
      float changey;
public Myanimation(Context context) {
super(context);
// TODO Auto-generated constructor stub
img=BitmapFactory.decodeResource(getResources(), R.drawable.r);
img1=BitmapFactory.decodeResource(getResources(), R.drawable.b);

changey = 0;
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(img, (canvas.getWidth()/2),changey,null);
canvas.drawBitmap(img1, (canvas.getWidth()/8),changey,null);

if(changey < canvas.getHeight())
{
changey +=5;
}else
{
changey =0;
}
invalidate();

}

}





Custom Buttons in Android

         Custom Buttons in Android




CustombuttondemoActivity.java


package a.b;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CustombuttondemoActivity extends Activity implements OnClickListener {
Button b1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b1=(Button)findViewById(R.id.button1);
        b1.setOnClickListener(this);
    }
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

}
}



main.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button
android:background="@drawable/custom"
android:layout_height="wrap_content"
android:id="@+id/button1"
android:layout_width="wrap_content"></Button>
<Button android:text="Button"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:layout_width="145dp"></Button>
</LinearLayout>



then create a xml file in the drawable folder

custom.xml


<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
  <item    android:state_pressed="true"   android:drawable="@drawable/b3"></item>
  <item  android:state_focused="true" android:drawable="@drawable/b2"></item>
  <item android:drawable="@drawable/b1"></item>
    
</selector>


following are the images for on selected ,on pressed and default states of button








Tuesday, 4 September 2012

Intent



Intent


Class gallery;
                            try
                            {
                            gallery=Class.forName("com.facebook.android.gallery");
                            Intent i=new Intent(Hackbook.this,gallery);
                            //   startActivityForResult(i,PICK_EXISTING_PHOTO_RESULT_CODE);
                                        startActivity(i);
                            }
                            catch(ClassNotFoundException e)
                            {
                            e.printStackTrace();
                            }