Pages

Thursday, August 18, 2011

Starting With Android – Tutorial 1


We will be presenting series of tutorial which will help you to start with android.

Setup environment for Development

> Android provide its own SDK for development, it's totally java based, if you are good in Core java than you are good to start with Android Development

> First of all you need to set up an IDE(Integrated Development environment) for development, all tutorial we will be sharing are build using Eclipse IDE with Android Plugin installed.

> Setup steps are very well demonstrated on android platform

http://developer.android.com/sdk/installing.html

Terms to understand before we begin

> ADT -> Android Development Tools
> AVD -> Android Virtual Device - This is an emulator which you can configure as a model of
 	 actual device.

Understanding Basic Structure of Android Application. 
Below listed are basic folders which you will be using while developing android application
Structure of Android Application

Name of folder itself will tell you little about what that folder will going to contain.
Let's start with them one by one and see if what you thought is right or otherwise.

1) res -> This folder contains all the resources which will be used inside applications. There are different folders for different type of resources

  a) drawable -> This will contain all the images which you will be using in your application.

  b) layout -> This folder will contain xml files. These xml files actually define the layout of   different screens of our application. Android provides a facility to define your screen
design in xml.  We will discuss these files in our later tutorials in more details

  c) values -> This folder contains different files for different type of key value pairs, 
which you will be using in your application. These files help in moving various type of constants from java code to configurable xml files. These have various advantages also such as ii8n, re-usability and maintenance of constants  and many more to explore.
  • String
  • Dimensions
  • Colors etc.
     d) raw -> This folder will contain files other than images such as music files, video files and other supported files.

 2) src  -> This folder contain all your java code
 3) lib -> This folder contain all external api jars which you want to use in your applications
 4) gen -> This is also java folder which is automatically generated by android. It will create a R.java file which will have  mapping for all files under /res folder. You can read more about R file from
 5) AndroidManifest.xml  -> This is configurable file for android application, this files contains configurations such as
       a) Minimum SDK application will be running on
       b) Different Uses Permission Application required
       c) Starting Screen of application
       d) And many more to explore
I hope this tutorial will help you in starting with android. We will soon be releasing other tutorials of these series.
Please share your comments and ratings, these will help us in improving and reaching more and more people.
You can also mail us on info@iotasol.com, or follow us on twitter @iotasol
You can also visit our websites www.iotasol.com and www.iotadomains.com

Monday, August 8, 2011

Zoom Image on Double Tap in android


 Zoom Image on Double Tap in android

The code below shows how we can zoom image on double tap in anroid, it's custom view class which will help us to make zoom image effect in anroid

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.widget.FrameLayout.LayoutParams;

/**
 * Custom class to zoom image in android
 *
 * @author Yash@iotasol.com
 */
public class ZoomImageView extends View implements OnGestureListener {

    private static final int SCALING_FACTOR = 50;
    private final int LANDSCAPE = 1;
    private GestureDetector gestureDetector;
    private Drawable image = null;
    private int scalefactor = 0;
    private int orientation;
    private int zoomCtr = 0;
    private long lastTouchTime = 0;
    private int winX, winY, imageX, imageY, scrollX = 0, scrollY = 0, left,
    top, bottom, right;

    public ZoomImageView(Context context, int orientation) {
        super(context);
        setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT));
        this.orientation = orientation;
        gestureDetector = new GestureDetector(this);
    }

   
    public void setImage(Drawable bitmap, Activity activity) {
        image = bitmap;
        imageSetting(activity);
    }

    public void setImage(Bitmap bitmap, Activity activity) {
        image = new BitmapDrawable(bitmap).getCurrent();
        imageSetting(activity);
    }

    /**
     * Works in both landscape and potrait mode.
     */
    private void imageSetting(Activity activity) {
        scrollX = scrollY = 0;
        scalefactor = 0;
        imageX = winX = activity.getWindow().getWindowManager()
                .getDefaultDisplay().getWidth();
        imageY = winY = activity.getWindow().getWindowManager()
                .getDefaultDisplay().getHeight();
        if (orientation == LANDSCAPE) {
            imageX = 3 * imageY / 4;
        }
        calculatePos();
    }

    public void calculatePos() {
        int tempx, tempy;
        tempx = imageX + imageX * scalefactor / 100;
        tempy = imageY + imageY * scalefactor / 100;
        left = (winX - tempx) / 2;
        top = (winY - tempy) / 2;
        right = (winX + tempx) / 2;
        bottom = (winY + tempy) / 2;
        invalidate();
    }

   
    /**
     * Redraws the bitmap when zoomed or scrolled.
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (image == null)
            return;

        image.setBounds(left + scrollX, top + scrollY, right + scrollX, bottom
                + scrollY);
        image.draw(canvas);
    }

    public void zoomIn() {
        scalefactor += SCALING_FACTOR;
        calculatePos();
    }

    public void zoomOut() {
        if (scalefactor == 0)
            return;
        scrollX = scrollY = 0;
        scalefactor -= SCALING_FACTOR;
        calculatePos();
    }

    public void scroll(int x, int y) {
        scrollX += x / 5;
        scrollY += y / 5;
        if (scrollX + left > 0) {
            scrollX = 0 - left;
        } else if (scrollX + right < winX) {
            scrollX = winX - right;
        }
        if (scrollY + top > 0) {
            scrollY = 0 - top;
        } else if (scrollY + bottom < winY) {
            scrollY = winY - bottom;
        }
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent me) {
        boolean onTouchEvent = gestureDetector.onTouchEvent(me);
        return onTouchEvent;
    }

    @Override
    public boolean onDown(MotionEvent arg0) {
        long thisTime = arg0.getEventTime();
        if (thisTime - lastTouchTime < 250) {
            lastTouchTime = -1;
            onDoubleTap();
            return true;
        }
        lastTouchTime = thisTime;
        return true;
    }
   
    @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                float distanceY) {
            if (zoomCtr == 0)
                return false;
            scroll((int) (e2.getX() - e1.getX()), (int) (e2.getY() - e1.getY()));
            return true;
        }
   
        private void onDoubleTap() {
            if (zoomCtr == 0) {
                zoomCtr++;
                zoomIn();
                return;
            }
            zoomCtr--;
            zoomOut();
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {
    }

   

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // TODO Auto-generated method stub
        return true;
    }
}


Below is the test class which is used as example to run the ZoomImageView

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

public class TestTapActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ZoomImageView imageView = new ZoomImageView(this, getWindow()
                .getWindowManager().getDefaultDisplay().getOrientation());
        imageView.setImage(this.getResources().getDrawable(R.drawable.sample1),
                this);

        this.setContentView(imageView);
    }
}


I hope this post will be helpful. 

Please share your comments and and you can also contact me @ info@iotasol.com or visit our site www.iotasol.com , www.iotadomains.com.

Friday, August 5, 2011

Starting With Android Programming: Creating Custom Horizontal Scroll View With Snap o...

Starting With Android Programming: Creating Custom Horizontal Scroll View With Snap o...: "I have faced various issues to develop a horizontal scroll view with paging effect. I googled it a lot but not able to find anything satisfa..."

Creating Custom Horizontal Scroll View With Snap or paging

I have faced various issues to develop a horizontal scroll view with paging effect. I googled it a lot but not able to find anything satisfactory. Some search results help me, using those i have created my own custom horizontal scrollview class which can give similar effect as effect on Tablet Home page.

I will be discussing it step by step so that you can use it where required and it becomes easy for you to understand.

Step 1) Layout file -  Simple layout file for demo


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_height="match_parent"
android:layout_width="match_parent" android:id="@+id/layer">
</LinearLayout>

Step 2) CustomHorizontalScrollView - Class file which extends HorizontalScrollView and give snapping or paging effect.


public class CustomHorizontalScrollView extends HorizontalScrollView implements
OnTouchListener, OnGestureListener {

        private static final int SWIPE_MIN_DISTANCE = 300;

private static final int SWIPE_THRESHOLD_VELOCITY = 300;
private static final int SWIPE_PAGE_ON_FACTOR = 10;


private GestureDetector gestureDetector;
private int scrollTo = 0;
private int maxItem = 0;
private int activeItem = 0;
private float prevScrollX = 0;
private boolean start = true;
private int itemWidth = 0;
private float currentScrollX;
private boolean flingDisable = true;

public CustomHorizontalScrollView(Context context) {
super(context);
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
}

public CustomHorizontalScrollView(Context context, int maxItem,
int itemWidth) {
this(context);
this.maxItem = maxItem;
this.itemWidth = itemWidth;
gestureDetector = new GestureDetector(this);
this.setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
Boolean returnValue = gestureDetector.onTouchEvent(event);

int x = (int) event.getRawX();

switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (start) {
this.prevScrollX = x;
start = false;
}
break;
case MotionEvent.ACTION_UP:
start = true;
this.currentScrollX = x;
int minFactor = itemWidth
/ ConfigurationParams.SWIPE_PAGE_ON_FACTOR;

if ((this.prevScrollX - this.currentScrollX) > minFactor) {
if (activeItem < maxItem - 1)
activeItem = activeItem + 1;

} else if ((this.currentScrollX - this.prevScrollX) > minFactor) {
if (activeItem > 0)
activeItem = activeItem - 1;
}
System.out.println("horizontal : " + activeItem);
scrollTo = activeItem * itemWidth;
this.smoothScrollTo(scrollTo, 0);
returnValue = true;
break;
}
return returnValue;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (flingDisable)
return false;
boolean returnValue = false;
float ptx1 = 0, ptx2 = 0;
if (e1 == null || e2 == null)
return false;
ptx1 = e1.getX();
ptx2 = e2.getX();
// right to left

if (ptx1 - ptx2 > ConfigurationParams.SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > ConfigurationParams.SWIPE_THRESHOLD_VELOCITY) {
if (activeItem < maxItem - 1)
activeItem = activeItem + 1;

returnValue = true;

} else if (ptx2 - ptx1 > ConfigurationParams.SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > ConfigurationParams.SWIPE_THRESHOLD_VELOCITY) {
if (activeItem > 0)
activeItem = activeItem - 1;

returnValue = true;
}
scrollTo = activeItem * itemWidth;
this.smoothScrollTo(0, scrollTo);
return returnValue;
}

@Override
public boolean onDown(MotionEvent e) {
return false;
}

@Override
public void onLongPress(MotionEvent e) {
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
return false;
}

@Override
public void onShowPress(MotionEvent e) {
}

@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
}



Step 3) TestHorizontalActivity- This class will be used as test class


public class TestHorizontalActivity extends Activity {

private LinearLayout linearLayout;
private CustomHorizontalScrollView horizontalScrollView;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
horizontalScrollView = new CustomHorizontalScrollView(this, 3,
width);
setContentView(R.layout.horizontal);
linearLayout = (LinearLayout) findViewById(R.id.layer);
linearLayout.addView(horizontalScrollView);

LinearLayout container = new LinearLayout(this);
container.setLayoutParams(new LayoutParams(width, height));
// container.setHeight(height);

TextView textView = new TextView(this);
textView.setWidth(width);
textView.setHeight(height);
textView.setGravity(Gravity.CENTER);
textView.setText("First  Screen");
textView.setBackgroundColor(Color.CYAN);
container.addView(textView);

textView = new TextView(this);
textView.setWidth(width);
textView.setHeight(height);
textView.setGravity(Gravity.CENTER);
textView.setText("Second  Screen");
textView.setBackgroundColor(Color.GREEN);
container.addView(textView);

textView = new TextView(this);
textView.setWidth(width);
textView.setHeight(height);
textView.setGravity(Gravity.CENTER);
textView.setText("Third  Screen");
textView.setBackgroundColor(Color.RED);
container.addView(textView);

horizontalScrollView.addView(container);
}

}


This is it, these 3 simple steps and you are ready to run a paging effect in your android application.

In next blog i will discuss how we can use combination of both horizontal scrolling and vertical scrolling.


I hope this post will be helpful. 

Please share your comments and and you can also contact me @ yash@iotasol.com or visit our site www.iotasol.com , www.iotadomains.com.

Wednesday, August 3, 2011

Extracting Zip File in Android

The code snippet below explains how to extract zip file in android
You can call extractZip method with activity from where its called and path of file to be extracted
It will extract the files on same destination path
/**
 * This method will extract the zip file from location inside application 
 * 
 * @param activity
 * @param destinationPath - Path of zip file
 * @param _location - location where file will be extracted
 * @author Yash@iotasol.com
 */
public void extractZip(Activity activity,String destinationPath,String _location ) {
System.out.println(" ctr : ::: extract zip" + zipExtracted + " : "
+ destinationPath);
FileInputStream fin = null;
ZipInputStream zin = null;
try {
fin = new FileInputStream(destinationPath);
zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
if (ze.isDirectory()) {
extractDirectoryZipEntry(ze.getName(), _location);
} else {
extractZipFileEntry(_location, zin, ze);
}
}
zipExtracted = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (zin != null) {
zin.close();
}
if (fin != null) {
fin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}



/**
 * This method will work on every single zip entry and store it in location
 * Buffered input stream is used to speed up the downloading process
 * @param _location
 * @param zin
 * @param ze
 * @author Yash@iotasol.com
 */
private void extractZipFileEntry(String _location, ZipInputStream zin,
ZipEntry ze) {
System.out.println(">>>>> file : " + ze.getName());
FileOutputStream fout = null;
BufferedOutputStream bout = null;
try {
fout = new FileOutputStream(_location + ze.getName());
bout = new BufferedOutputStream(fout, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = zin.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
}
} catch (Exception r) {
r.printStackTrace();
} finally {
try {
zin.closeEntry();
if (bout != null)
bout.close();
if (fout != null)
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(">>>>> file downloaded: " + ze.getName());
}


/**
 * This method will work on every single zip entry in case if its a directory, and creates new
 * 
 * @param dir
 * @param _location
 * @author Yash@iotasol.com
 */
private void extractDirectoryZipEntry(String dir, String _location) {

File f = new File(_location + dir);

if (!f.isDirectory()) {
f.mkdirs();
}
}


I hope this post will be helpful. 

Please share your comments and and you can also contact me @ yash@iotasol.com or visit our site www.iotasol.com , www.iotadomains.com.