Search This Blog

Sunday 29 April 2012

Service example in android

Service is one of core component of android application. Every one knows service is very important part. we use it but sometimes we do not know exact power and depth of service, today i am going to discuss it in details.
After this article we will also let you know difference between Thread and Service, and how to perform real time task in service


In the end you will also get source code.

Service -A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

Difference between a Thread , service and asynchronous task

1)  Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.

2)  A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.

3)  An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components

Other one difference between service and thread is that thread is not intelligent enough to recognize that is it already running or not? Every time you create a new object of thread and start again it will create a new instance and a new thread start running.
But if service is already running and you start again it will not created again.So that is very important difference

Saturday 28 April 2012

Utility Function Call, Email, Send SMS in android Using Intent

Generally while we making an android application then sometimes we need small piece of code like how to call a number on button click, how to send an email, how to send a sms. But problem is that it does not available at one place. So i am giving all possible Utility code here

1) How to call a number in android application

 Intent callIntent = new Intent(Intent.ACTION_CALL);  
 callIntent.setData(Uri.parse("tel:123456789"));  
 startActivity(callIntent);  


2) How to send an email in android application

 Intent(android.content.Intent.ACTION_SENDTO);
emailIntent.setType("text/html");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "testing email send.");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<b>this is html text in email body.</b>"));
startActivity(Intent.createChooser(emailIntent, "Email to Friend")); 

How to pick an Email from contact in android

Picking email, Phone number, and other detail from android in built contact is very easy if you use ACTION_PICK.Action Pick activity syntax will be like


Intent intent1=new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent1,100);


Note : it need permission .so do not forget to mention it in manifest

<uses-permission android:name="android.permission.READ_CONTACTS"/>

It will start a default activity that will list all contact. On item select that activity will finish automatically and it will return result in OnActivityResult. default activity return complete Intent with all available information with particular select contact.

Saturday 21 April 2012

How to write a good resume

Resume is face of any employee.Generally while we are writing resume we commit a lot of mistake unknowingly so we left unnoticed . While we are first interacting with Employer then Resume will tell everything about you. So writing resume is key  to create a first impression on our Employer.I am going to explain about how much we have to focus on which segment..

1)Always prefer Descending order of your experience or education 

As while we went on to achieve in life then it became more focus and specific about our goal and our work.So always follow the descending order.It will directly show your latest work to Employer.This increase your chance of your getting noticed.


2) Be Specific about your current job requirement 

Its not good idea to generalize your work or using single format and data for every job.Each job need some specific requirement .So your focus and format should be current job . And do a little bit of change while sending resume to current job

Let a example if you worked on .Net for three year and one year on android.Now you are applying for an android developer job.So in this case your main focus should be on android(Achievement and work in android)

Thread Synchronization in Java and Android

Java is always fun love for me. Thread was the only thing that make feared so study it hard and now want to make sure that it will not happen with any one now. I have discussed about how to create simple Thread. But most important is to Synchronization of two thread.

For example -We have one file. And we have two thread one for reading this file and second for writing file. So in this case if we want to read everything that has to be written by write thread.Then Read thread to wait (if write is running) until Write does not complete it task.

For Thread Synchronization important thing is to note that we can synchronize only on one object.
Although i will write code in android technology but in java and Blackberry its almost same.For this i need to take two thread

Thread 1

private class Thread2 extends Thread{
        
        private SynDemo d;
        public Thread2(SynDemo sDemo) {
            d=sDemo;
        }
        @Override
        public void run() {
            super.run();
            d.printNumber("Thread2");
        }
    }                                                                           

This Thread will print number from 0 to 2000.Next thread also will doing the same.

Thread 2

Thursday 19 April 2012

Simple Thread example in java

Before posting this example i would to thank Herbert Shield


The simple example shown in full on the previous page defines two classes: SimpleThread and TwoThreadsTest. Let's begin our exploration of the application with the SimpleThread class: a subclass of the Thread class that is provided by the java.lang package.
class SimpleThread extends Thread {
    public SimpleThread(String str) {
 super(str);
    }
    public void run() {
 for (int i = 0; i < 10; i++) {
     System.out.println(i + " " + getName());
            try {
  sleep((int)(Math.random() * 1000));
     } catch (InterruptedException e) {}
 }
 System.out.println("DONE! " + getName());
    }
}
The first method in the SimpleThread class is a constructor that takes a String as its only argument. This constructor is implemented by calling a superclass constructor and is only interesting to us because it sets the Thread's name which is used later in the program.
The next method in the SimpleThread class is the run() method. The run() method is the heart of any Thread--it's where the action of the Thread takes place. The run() method of the SimpleThread class contains a for loop that iterates ten times. In each iteration the method displays the iteration number and the name of the Thread then sleeps for a random interval between 0 and 1 second. After the loop has finished, the run() method prints "DONE!" along with the name of the thread. That's it for the SimpleThread class.
The TwoThreadsTest class provides a main() method that creates two SimpleThread threads: one is named "Jamaica" and the other is named "Fiji". (If you can't decide on where to go for vacation you can use this program to help you decide--go to the island whose thread prints "DONE!" first.)
class TwoThreadsTest {
    public static void main (String args[]) {
        new SimpleThread("Jamaica").start();
        new SimpleThread("Fiji").start();
    }
}

Tuesday 17 April 2012

Displaying Bitmaps Efficiently and Avoiding java.lang.OutofMemoryError

java.lang.OutofMemoryError: bitmap size exceeds VM budget. This is most common error for us when we are decoding Bitmap more than 4 MB. In generally before decoding bitmap we do not know how much bigger the size of a bitmap will be. So its very difficult problem for us to handle this error in proactive approach

But good thing is that android provide a way to handle this problem.Before decoding bitmap we just decode it with options.inJustDecodeBounds = true. options is the instance of BitmapFactory. It does not load bitmap into memory but it help us to find the width and height of a bitmap so that we can reduce the height and width according to our device

As Bitmaps take up a lot of memory, especially for rich images like photographs. For example, the camera on the Galaxy Nexus takes photos up to 2592x1936 pixels (5 megapixels). If the bitmap configuration used is ARGB_8888 (the default from the Android 2.3 onward) then loading this image into memory takes about 19MB of memory (2592*1936*4 bytes), immediately exhausting the per-app limit on some devices.

So we will find actual height and width of a bitmap as follows...

Home screen widget , Weather widget in android

Home-Screen widget are best when your application is running in background and you want to show progress update and related information on home screen.
For example-You are playing song in MediaPlayer and want to show progress on home screen about currently playing song and other information

So for this we need three classes and in the end of this article i have posted full source code link


  • WeatherDataProvider — Our ContentProvider which stores the weather data for this sample. Note that for simplicity, it currently stores the data in memory as opposed to an external and persistent storage such as a file, network location, database, or shared preference.
  • WeatherWidgetProvider — Our AppWidgetProvider which handles specific intent actions (such as when an item is clicked, or the refresh button is pressed). It also sets up the RemoteViews for the widget and binds the service to the collection view in the widget.
  • WeatherWidgetService — Our RemoteViewsService which manages the creation of new factories, which return the RemoteViews for each item in the ListView.   
Screen shot of this application will be like that


Monday 16 April 2012

Creating HorizontalScrollView in Android

Today i am going to describing a powerful tool of android, Horizontal Listview with complete source in the end.
Horizontal ListView sometimes is very useful and it save our day. HorizontalScrollView is nothing but a widget, If you add more element than its visible area then it start scrolling horizontally. Bit main disadvantage is that you can not perform click on the base of position quite easily

If you need some explanation then read complete step else download code with link in the end and play with it

Step 1) Create one new Project name HorizontalListviewDemo

Step 2) Change your main activity to as follow class

 package com.ahmad;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.LinearLayout;  
 import android.widget.Toast;  
 public class SecondActivity extends Activity implements OnClickListener {  
  Button btn1, btn2, btn3, btn4;  
  public LinearLayout middle;  
  @Override  
  public void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
     setContentView(R.layout.main);  
  btn1 = (Button) findViewById(R.id.btn1);  
  btn1.setOnClickListener(this);  
  btn2 = (Button) findViewById(R.id.btn2);  
  btn2.setOnClickListener(this);  
  btn3 = (Button) findViewById(R.id.btn3);  
  btn3.setOnClickListener(this);  
  try {  
   btn4 = (Button) findViewById(R.id.btn4);  
   btn4.setOnClickListener(this);  
  } catch (Exception e) {  
   e.getMessage();  
  }  
  }  
  @Override  
  public void onClick(View v) {  
  if (v.getId() == R.id.btn1) {  
   Toast.makeText(this, "Second Act Btn1 Clicked", Toast.LENGTH_LONG)  
    .show();  
  } else if (v.getId() == R.id.btn2) {  
   Toast.makeText(this, "Second Act Btn 2 Clicked", Toast.LENGTH_LONG)  
    .show();  
  } else if (v.getId() == R.id.btn3) {  
   Toast.makeText(this, "Second Act Btn 3 Clicked", Toast.LENGTH_LONG)  
    .show();  
  } else if (v.getId() == R.id.btn4) {  
   Toast.makeText(this, "Second Act Btn 4 Clicked", Toast.LENGTH_LONG)  
    .show();  
  }  
  }  
 }  
Step 3)Make one Layout and add HorizontalListview and some content inside

  
Now enjoy after running it.complete source link is below.See more article on ListView in blog tag Android ListView
                                                          Download Complete Project


Article You may Like

Android Listactivity with header

Sunday 15 April 2012

Asynchronous task, Updating UI from background in android

As all we know in android there are two ways to perform background task such as downloading image and other task that include long operation
  • Using Thread 
  • Asynchronous Task                          
Using Thread, there is one dis-advantage that we can not update user interface other wise we will get Looper.loop() exception

So its efficient to use Asynchronous task.
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, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

Saturday 14 April 2012

Zipping File and Folder in android

While we are attaching any folder/file to mail or other attachment so we really need to attach folder with more than one sub folder. So we need to compress it so called zipping . It necessary in Mobile OS as in Windows. So for this android provide ZipOutPutStream and ZipEntry. ZipOutPutStream read complete folder and then ZipEntry zip all the file inside folder to a new compress folder. Zipping File is very easy.If you want dynamically select which file/folder to zipped then see this

import android.util.Log; 
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipOutputStream; 
 
 
public class Compress { 
  private static final int BUFFER = 2048; 
 
  private String[] _files; 
  private String _zipFile; 
 
  public Compress(String[] files, String zipFile) { 
    _files = files; 
    _zipFile = zipFile; 
  } 
 
  public void zip() { 
    try  { 
      BufferedInputStream origin = null; 
      FileOutputStream dest = new FileOutputStream(_zipFile); 
 
      ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); 
 
      byte data[] = new byte[BUFFER]; 
 
      for(int i=0; i < _files.length; i++) { 
        Log.v("Compress", "Adding: " + _files[i]); 
        FileInputStream fi = new FileInputStream(_files[i]); 
        origin = new BufferedInputStream(fi, BUFFER); 
        ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1)); 
        out.putNextEntry(entry); 
        int count; 
        while ((count = origin.read(data, 0, BUFFER)) != -1) { 
          out.write(data, 0, count); 
        } 
        origin.close(); 
      } 
 
      out.close(); 
    } catch(Exception e) { 
      e.printStackTrace(); 
    } 
 
  } 
} 

In constructor we have two string parameter.first pass array of file inside a folder .Then file path to which zipped folder will save if it is not present then this code will create new zip folder.

Friday 13 April 2012

Android File explorer example i.e pick image, video, Audio from android sdcards

In android we know sdcard is main drive to store information. Sometimes we need to read/write file from sdcard. In this case we can give static path and easily can read/write using FileInputStream and FileOutputStream. But in most case we need to select it  dynamically on user demand.After selecting it we can modify it, we can share or we can send it to anywhere

So today I am going to make a simple application like File-explorer. It will help in my next Article Ziping and Unziping Folder in android.


Step1) Create one project File-Explorer 


Step 2) Change your activity to following code

package com.AndroidExplorer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidExplorer extends ListActivity {
 private List<String> item = null;
 private List<String> path = null;
 private String root = "/sdcard";
 private TextView myPath;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.explorer);
  myPath = (TextView) findViewById(R.id.path);
  getDir(root);
 }
 private void getDir(String dirPath) {
  myPath.setText("Location: " + dirPath);
  item = new ArrayList<String>();
  path = new ArrayList<String>();
  File f = new File(dirPath);
  File[] files = f.listFiles();
  if (!dirPath.equals(root)) {
   item.add(root);
   path.add(root);
   item.add("../");
   path.add(f.getParent());
  }
  for (int i = 0; i < files.length; i++) {
   File file = files[i];
   path.add(file.getPath());
   if (file.isDirectory())
    item.add(file.getName() + "/");
   else
    item.add(file.getName());
  }
  ArrayAdapter<String> fileList = new ArrayAdapter<String>(this,
    R.layout.explorer_row, item);
  setListAdapter(fileList);
         }
       File file;
       @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
 file = new File(path.get(position));
  if (file.isDirectory()) {
    if (file.canRead())
    getDir(path.get(position));
   else {
    new AlertDialog.Builder(this)
    .setIcon(R.drawable.icon)
    .setTitle("[" + file.getName()+ "] folder can't be read!")
    .setPositiveButton("OK",new DialogInterface.OnClickListener() {
       @Override public void onClick(DialogInterface dialog,int which) {
     }}).show();
   }
  } else {
      new AlertDialog.Builder(this)
     .setIcon(R.drawable.icon)
     .setTitle("Select")
     setMessage("Select " + file.getName() + "to server ?")
    .setPositiveButton("Select",new DialogInterface.OnClickListener() {
         @Override public void onClick(DialogInterface dialog,int which) {
  Toast.makeText(
                     AndroidExplorer.this,"" + file.getAbsolutePath()+ " iss selected ",300)
           .show();
     }
 })
 .setNegativeButton("No",new DialogInterface.OnClickListener() {
  @Override
          public void onClick(DialogInterface dialog,int which) {
         dialog.dismiss();
      }
   }).show();
  }
     }
      } 


Step 3)Now our coding part has been done.

We will create two xml. As i have take one List-Activtiy   so it need two layout one main.xml and another one to inflating into ListView row.Click me for advance ListView

  • explorer.xml inside res/layout folder
<?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:id="@+id/path"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<ListView
 android:id="@android:id/list"
 android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:cacheColorHint="#B26B00"
    android:fadingEdge="none"
 />
<TextView
 android:id="@android:id/empty"
 android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="No Data"
 />
</LinearLayout>
  • explorer_row in same folder
<?xml version="1.0" encoding="utf-8"?>
<TextView 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rowtext" android:padding="10dp"
  android:background="#C0C0C0" android:textColor="#000"
  android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:textSize="23sp" />

Now enjoy you can download this complete project from this link.

                                      Download this Project


These are the screen shot of that project




Saturday 7 April 2012

Pinching Zoom in android Image View or Bitmap

See Updated Tutorial


This is little bit complex article. In android , we can achieve pinch zoom with two or more than two finger. But it s little bit complex. I have developed it with the help of one GuitHub project.

Here we use Bitmap, Gesture, Matrix and other Bitmap Basic function. I have develop simply three classes.
main class is TouchImageView.java that is a Image-View.you can set this class Object anywhere

Make one project and use my classes

main class TouchImageView.java 

 package com.ahmad;  
 import android.content.Context;  
 import android.graphics.Bitmap;  
 import android.graphics.Matrix;  
 import android.graphics.PointF;  
 import android.util.FloatMath;  
 import android.util.Log;  
 import android.view.MotionEvent;  
 import android.view.View;  
 import android.widget.ImageView;  
 public class TouchImageView extends ImageView  
 {  
   private static final String TAG = "Touch";  
   Matrix matrix = new Matrix();  
   Matrix savedMatrix = new Matrix();  
   // We can be in one of these 3 states  
   static final int NONE = 0;  
   static final int DRAG = 1;  
   static final int ZOOM = 2;  
   int mode = NONE;  
   // Remember some things for zooming  
   PointF start = new PointF();  
   PointF mid = new PointF();  
   float oldDist = 1f;  
   Context context;  
   public TouchImageView(Context context)  
   {  
     super(context);  
     super.setClickable(true);  
     this.context = context;  
     matrix.setTranslate(1f, 1f);  
     setImageMatrix(matrix);  
     setScaleType(ScaleType.MATRIX);  
     setOnTouchListener(new OnTouchListener()  
     {  
       @Override  
       public boolean onTouch(View v, MotionEvent rawEvent)  
       {  
         WrapMotionEvent event = WrapMotionEvent.wrap(rawEvent);  
         // Dump touch event to log  
         // if (Viewer.isDebug == true)  
         {  
           // dumpEvent(event);  
           //  
         }  
         // Handle touch events here...  
         switch (event.getAction() & MotionEvent.ACTION_MASK)  
         {  
           case MotionEvent.ACTION_DOWN:  
           savedMatrix.set(matrix);  
           start.set(event.getX(), event.getY());  
           Log.d(TAG, "mode=DRAG");  
           mode = DRAG;  
           break;  
           case MotionEvent.ACTION_POINTER_DOWN:  
           oldDist = spacing(event);  
           Log.d(TAG, "oldDist=" + oldDist);  
           if (oldDist &gt; 10f)  
           {  
             savedMatrix.set(matrix);  
             midPoint(mid, event);  
             mode = ZOOM;  
             Log.d(TAG, "mode=ZOOM");  
           }  
           break;  
           case MotionEvent.ACTION_UP:  
           int xDiff = (int) Math.abs(event.getX() - start.x);  
           int yDiff = (int) Math.abs(event.getY() - start.y);  
           if (xDiff &lt; 8 && yDiff &lt; 8)  
           {  
             performClick();  
           }  
           case MotionEvent.ACTION_POINTER_UP:  
           mode = NONE;  
           Log.d(TAG, "mode=NONE");  
           break;  
           case MotionEvent.ACTION_MOVE:  
           if (mode == DRAG)  
           {  
             // ...  
             matrix.set(savedMatrix);  
             matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);  
           }  
           else if (mode == ZOOM)  
           {  
             float newDist = spacing(event);  
             Log.d(TAG, "newDist=" + newDist);  
             if (newDist &gt; 10f)  
             {  
               matrix.set(savedMatrix);  
               float scale = newDist / oldDist;  
               matrix.postScale(scale, scale, mid.x, mid.y);  
             }  
           }  
           break;  
         }  
         setImageMatrix(matrix);  
         return true; // indicate event was handled  
       }  
     }  
     );  
   }  
   public void setImage(Bitmap bm, int displayWidth, int displayHeight)  
   {  
     super.setImageBitmap(bm);  
     //Fit to screen.  
     float scale;  
     if ((displayHeight / bm.getHeight()) &gt;= (displayWidth / bm.getWidth()))  
     {  
       scale = (float)displayWidth / (float)bm.getWidth();  
     }  
     else  
     {  
       scale = (float)displayHeight / (float)bm.getHeight();  
     }  
     savedMatrix.set(matrix);  
     matrix.set(savedMatrix);  
     matrix.postScale(scale, scale, mid.x, mid.y);  
     setImageMatrix(matrix);  
     // Center the image  
     float redundantYSpace = (float)displayHeight - (scale * (float)bm.getHeight()) ;  
     float redundantXSpace = (float)displayWidth - (scale * (float)bm.getWidth());  
     redundantYSpace /= (float)2;  
     redundantXSpace /= (float)2;  
     savedMatrix.set(matrix);  
     matrix.set(savedMatrix);  
     matrix.postTranslate(redundantXSpace, redundantYSpace);  
     setImageMatrix(matrix);  
   }  
   /** Show an event in the LogCat view, for debugging */  
   @SuppressWarnings("unused")  
   private void dumpEvent(WrapMotionEvent event)  
   {  
     String names[] =  
     {  
       "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",  
       "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?"  
     }  
     ;  
     StringBuilder sb = new StringBuilder();  
     int action = event.getAction();  
     int actionCode = action & MotionEvent.ACTION_MASK;  
     sb.append("event ACTION_").append(names[actionCode]);  
     if (actionCode == MotionEvent.ACTION_POINTER_DOWN  
     || actionCode == MotionEvent.ACTION_POINTER_UP)  
     {  
       sb.append("(pid ").append(  
       action &gt;&gt; MotionEvent.ACTION_POINTER_ID_SHIFT);  
       sb.append(")");  
     }  
     sb.append("[");  
     for (int i = 0; i &lt; event.getPointerCount(); i++)  
     {  
       sb.append("#").append(i);  
       sb.append("(pid ").append(event.getPointerId(i));  
       sb.append(")=").append((int) event.getX(i));  
       sb.append(",").append((int) event.getY(i));  
       if (i + 1 &lt; event.getPointerCount())  
       sb.append(";");  
     }  
     sb.append("]");  
     Log.d(TAG, sb.toString());  
   }  
   /** Determine the space between the first two fingers */  
   private float spacing(WrapMotionEvent event)  
   {  
     float x = event.getX(0) - event.getX(1);  
     float y = event.getY(0) - event.getY(1);  
     return FloatMath.sqrt(x * x + y * y);  
   }  
   /** Calculate the mid point of the first two fingers */  
   private void midPoint(PointF point, WrapMotionEvent event)  
   {  
     float x = event.getX(0) + event.getX(1);  
     float y = event.getY(0) + event.getY(1);  
     point.set(x / 2, y / 2);  
   }  
 }  

How to create a simple android Gallery View

Android provide a way to show photo (either from sdcards or on-line) in a specified manner. You can navigate and see all photo. We do with help of android widget Gallery. Gallery is just like List View in which we bind the data using Base Adapter . If want some depth knowledge about how to bind data using adapter then see ListView with Image and Text Article.
Gallery is deprecated from Jelly bean. And they suggest to use  horizontally scrolling widgets include Horizontal Scroll-view and View Pager from the support library.Wait soon i will post about this also. But for now we can use Gallery.

Step1) First create a new project

Step2 change your main.xml to as follows

  <?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" android:padding="5dp">

       <Gallery

android:id="@+id/Gallery01"

android:layout_width="fill_parent"

android:layout_height="90dp"></Gallery>

        <LinearLayout

android:id="@+id/ImageView01"

android:layout_width="fill_parent"

android:layout_height="fill_parent"></LinearLayout>

</LinearLayout>


Step3 change your main activity to as follows- 


package com.ahmad.samples.views;


import android.app.Activity;

import android.content.Context;

import android.content.res.TypedArray;

import android.os.Bundle;

import android.view.Gravity;

import android.view.View;

import android.view.ViewGroup;

import android.view.ViewGroup.LayoutParams;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.BaseAdapter;

import android.widget.Gallery;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.Toast;


public class GalleryViewAhmad extends Activity {

        //These image should be store in your drawble folder under res.

Integer[] pics = { R.drawable.antartica1, R.drawable.antartica2,

R.drawable.antartica3, R.drawable.antartica4,

R.drawable.antartica5, R.drawable.antartica6,

R.drawable.antartica7, R.drawable.antartica8,

R.drawable.antartica9, R.drawable.antartica10 ,

R.drawable.antartica3, R.drawable.antartica4,

R.drawable.antartica5, R.drawable.antartica6,

R.drawable.antartica7, R.drawable.antartica8,

R.drawable.antartica9, R.drawable.antartica10 };

LinearLayout imageView;


/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

try {

// InputStream in = (new URL("www.google.com").openStream());

} catch (Exception e) {

e.getMessage();

}

Gallery ga = (Gallery) findViewById(R.id.Gallery01);

ga.setAdapter(new ImageAdapter(this));


imageView = (LinearLayout) findViewById(R.id.ImageView01);

ga.setOnItemClickListener(new OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,

long arg3) {

Toast.makeText(

getBaseContext(),

"You have selected picture " + (arg2 + 1)

+ " of Antartica", Toast.LENGTH_SHORT).show();

try {

imageView.removeAllViews();

} catch (Exception e) {

e.getMessage();

}

TouchImageView touchImageView = new TouchImageView(

GalleryView.this);

touchImageView.setImageResource(pics[arg2]);

LayoutParams lp=new LayoutParams(LayoutParams.FILL_PARENT,     LayoutParams.FILL_PARENT);

imageView.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);

touchImageView.setLayoutParams(lp);

imageView.addView(touchImageView);

}


});

}

This is Base-Adapter class to bind view with Gallery-View


public class ImageAdapter extends BaseAdapter {

private Context ctx;

int imageBackground;

public ImageAdapter(Context c) {

ctx = c;

TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);

imageBackground = ta.getResourceId(

R.styleable.Gallery1_android_galleryItemBackground, 1);

ta.recycle();

}

@Override

public int getCount() {

return pics.length;

}

@Override

public Object getItem(int arg0) {

return arg0;

}

@Override

public long getItemId(int arg0) {

return arg0;

}

@Override

public View getView(int arg0, View arg1, ViewGroup arg2) {

ImageView iv = new ImageView(ctx);

iv.setImageResource(pics[arg0]);

iv.setScaleType(ImageView.ScaleType.FIT_XY);

iv.setLayoutParams(new Gallery.LayoutParams(150, 120));

iv.setBackgroundResource(imageBackground);

return iv;

}

}

}




Now enjoy by running it.You can                download complete project

Wednesday 4 April 2012

Android: Creating custom alert dialog

In android sometimes we want to display some data but we do not want to start a new activity.As starting a new activity is not feasible in some cases.So what should we do?

First take a case

We have news showing in List-View now if some one click on on particular news then it should show detail about this this news.so instead of starting new activity we can just pop a custom dialog (with same view as activity) then we will use a custom dialog for this. Because of its benefit we call this custom dialog as Dialog activity

Step 1) Create a new project in android

Step 2) Change your main.xml as follows

  <?xml version="1.0" encoding="utf-8" ?>  
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">  
     <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start" android:id="@+id/show_dialog" />  
  </LinearLayout>  


Android News and source code