Thursday 20 December 2012

Difference between DELETE,TRUNCATE and DROP commands

DELETE

The DELETE command is used to remove rows from a table.
After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction
to make the change permanent or to undo it.

Note that this operation will cause all DELETE triggers on the table to fire.

TRUNCATE

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired.
As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE.

DROP

The DROP command removes a table from the database. All the tables' rows,
indexes and privileges will also be removed. No DML triggers will be fired.This operation cannot be rolled back

Tuesday 18 December 2012

Difference Between query and rawQuery in Android

In Android  Executing Queries using below methods

    Execute db.rawQuery method
    Execute db.query method


To execute a raw query to retrieve all departments:

Cursor getAllDepts()
  {
   SQLiteDatabase db=this.getReadableDatabase();
   Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,
        "+colDeptName+" from "+deptTable,new String [] {});

   return cur;
  }

The rawQuery method has two parameters:

    String query: The select statement
    String[] selection args: The arguments if a WHERE clause is included in the select statement

Notes
The result of a query is returned in Cursor object.In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .

Another way to perform a query is to use a db.query method. A query to select all employees in a certain department from a view would be like this:

public Cursor getEmpByDept(String Dept) {
   SQLiteDatabase db=this.getReadableDatabase();
   String [] columns=new String[]{"_id",colName,colAge,colDeptName};
   Cursor c=db.query(viewEmps, columns, colDeptName+"=?",
        new String[]{Dept}, null, null, null);
   return c;
  }

The db.query has the following parameters:

    String Table Name: The name of the table to run the query against
    String [ ] columns: The projection of the query, i.e., the columns to retrieve
    String WHERE clause: where clause, if none pass null
    String [ ] selection args: The parameters of the WHERE clause
    String Group by: A string specifying group by clause
    String Having: A string specifying HAVING clause
    String Order By by: A string Order By by clause

Content From:-shuklaxyz

Thursday 22 November 2012

Show the list of Available Sensors in Android

In Android we can find sensor list by using (android.hardware.SensorManager) class.

Steps:

1) Get SensorManager object

SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

2) SensorManager provide a method getSensorList() method

using above method with parameter Sensor.TYPE_ALL to get all the sensors

Below code shows listofSensors

List<Sensor> listofSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);

Output Screenshot:




















Android Activity(MainActivity.java)

package com.androidsurya.androidsensorlist;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SensorManager sensorManager = (SensorManager)                                    getSystemService(Context.SENSOR_SERVICE);
List<Sensor> listofSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);

List<String> listSensorTypes = new ArrayList<String>();
for (int i = 0; i < listofSensors.size(); i++) {
listSensorTypes.add(listofSensors.get(i).getName());
}

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listSensorTypes));
getListView().setTextFilterEnabled(true);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Register Activity in Android Manifest file

 <activity
            android:name="com.androidsurya.androidsensorlist.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>




Saturday 10 November 2012

Insert and Retrieve Image from SQLite Database Android Example

So many people are confuse which data type is best for insert large amount of data(like images) in to database. At that point of time in SQLite (BLOB) type is prefer and this will be store binary data nothing but a byte array data.(Converting our image to byte array and store into SQLite)

Here we See One Example which is Store Employee Details Like

Employee Name
Employee Photo
Employee Age

For Employee Name we use text datatype and for Employee Age integer datatype.But to Store Employee Photo which datatype ? at that time we use BLOB datatype.

insertEmpDetails() method which is taken Employee Class as parameter and it store all Employee information into Employees Table.
here we can see before inserting image into database,we should  be convert your Bitmap image to byte array for that we are using Utility class getBytes()method.

retriveEmpDetails() method which is retrieve Employee Details from Database and return Employee Object.
To get all Name,Photo,Age we use Corresponding getXXX() methods.
At the time of retriving photo we will get blob[] array of image.at that time we need to convert byte array to image.for that purpose we use getPhoto() method in Utility class which will convert our blob array into Bitmap image and retrun Bitmap image.

UI Layout(activity_main.xml)

This layout used to view 

Employee Name
Employee Photo
Employee Age

<?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" >

    <ImageView
        android:id="@+id/ivMain"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EMPLOYEE_NAME" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:text="NAME" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EMPLOYEE_PHOTO" />

        <ImageView
            android:id="@+id/photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/text3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EMPLOYEE_AGE" />

        <TextView
            android:id="@+id/age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:text="AGE" />
    </LinearLayout>

</LinearLayout>


Android Activity(InsertandRetriveBlobData.java)

package com.androidsurya.sqliteexample;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class InsertandRetriveBlobData extends Activity {
private DBhelper DbHelper;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DbHelper = new DBhelper(this);
Employee employee_One = new Employee(BitmapFactory.decodeResource(
getResources(), R.drawable.photo), "Surya", 25);
DbHelper.open();
DbHelper.insertEmpDetails(employee_One);
DbHelper.close();
employee_One = null;
DbHelper.open();
employee_One = DbHelper.retriveEmpDetails();
DbHelper.close();

TextView empname = (TextView) findViewById(R.id.name);
empname.setText(employee_One.getName());
ImageView empphoto = (ImageView) findViewById(R.id.photo);
empphoto.setImageBitmap(employee_One.getBitmap());
TextView empage = (TextView) findViewById(R.id.age);
empage.setText("" + employee_One.getAge());

}
}

DBhelper.java

This is database class here we declare

insertEmpDetails() method to insert employee details and
retriveEmpDetails() method to retrive employee details 

package com.androidsurya.sqliteexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBhelper {
public static final String EMP_ID = "id";
public static final String EMP_NAME = "name";
public static final String EMP_AGE = "age";
public static final String EMP_PHOTO = "photo";

private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "EmployessDB.db";
private static final int DATABASE_VERSION = 1;

private static final String EMPLOYEES_TABLE = "Employees";

private static final String CREATE_EMPLOYEES_TABLE = "create table "
+ EMPLOYEES_TABLE + " (" + EMP_ID
+ " integer primary key autoincrement, " + EMP_PHOTO
+ " blob not null, " + EMP_NAME + " text not null unique, "
+ EMP_AGE + " integer );";

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_EMPLOYEES_TABLE);
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + EMPLOYEES_TABLE);
onCreate(db);
}
}

public void Reset() {
mDbHelper.onUpgrade(this.mDb, 1, 1);
}

public DBhelper(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}

public DBhelper open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}

public void close() {
mDbHelper.close();
}

public void insertEmpDetails(Employee employee) {
ContentValues cv = new ContentValues();
cv.put(EMP_PHOTO, Utility.getBytes(employee.getBitmap()));
cv.put(EMP_NAME, employee.getName());
cv.put(EMP_AGE, employee.getAge());
mDb.insert(EMPLOYEES_TABLE, null, cv);
}

public Employee retriveEmpDetails() throws SQLException {
Cursor cur = mDb.query(true, EMPLOYEES_TABLE, new String[] { EMP_PHOTO,
EMP_NAME, EMP_AGE }, null, null, null, null, null, null);
if (cur.moveToFirst()) {
byte[] blob = cur.getBlob(cur.getColumnIndex(EMP_PHOTO));
String name = cur.getString(cur.getColumnIndex(EMP_NAME));
int age = cur.getInt(cur.getColumnIndex(EMP_AGE));
cur.close();
return new Employee(Utility.getPhoto(blob), name, age);
}
cur.close();
return null;
}
}

Utility.java

Utility class is main role here
Before inserting image and retrive image from SQLite Database we use these below methods.
getBytes() Convert bitmap image to byte array and retrun byte[]
getPhoto() convert byte[] to bitmap and retrun bitmap image

package com.androidsurya.sqliteexample;

import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

public class Utility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}

// convert from byte array to bitmap
public static Bitmap getPhoto(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}

Register Android Activity in AndroidManifest file

 <activity
            android:name="com.androidsurya.sqliteexample.InsertandRetriveBlobData"
            android:label="@string/app_name" >

Output Screenshot 




















Next Example using Sqlite Database

How to insert multiple images and retrieve multiple images from sqlite database example in Android.

http://androidsurya.blogspot.in/2014/01/multiple-images-insert-and-retrieve.html

Review/Feedback are always welcome :)







Thursday 8 November 2012

Drag to Refresh or Update ListView in Android

The below example will allow to user to pulling down and releasing from the top of the listview and refresh the Listview.

Output Screenshots:
















































Click on Below Button to Get Source code.






















Android Pull to Refresh ListView Example

The below example will allow to user to pulling down and releasing from the top of the listview and refresh the Listview.

Output Screenshots:

















































First Create custom view(PullToRefreshListView.java under com.androidsurya.customviews Package)

package com.androidsurya.customviews;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidsurya.pulltorefresh.R;


public class PullToRefreshListView extends ListView implements OnScrollListener {

    private static final int TAP_TO_REFRESH = 1;
    private static final int PULL_TO_REFRESH = 2;
    private static final int RELEASE_TO_REFRESH = 3;
    private static final int REFRESHING = 4;

    private static final String TAG = "PullToRefreshListView";

    private OnRefreshListener mOnRefreshListener;

    /**
     * Listener that will receive notifications every time the list scrolls.
     */
    private OnScrollListener mOnScrollListener;
    private LayoutInflater mInflater;

    private RelativeLayout mRefreshView;
    private TextView mRefreshViewText;
    private ImageView mRefreshViewImage;
    private ProgressBar mRefreshViewProgress;
    private TextView mRefreshViewLastUpdated;

    private int mCurrentScrollState;
    private int mRefreshState;

    private RotateAnimation mFlipAnimation;
    private RotateAnimation mReverseFlipAnimation;

    private int mRefreshViewHeight;
    private int mRefreshOriginalTopPadding;
    private int mLastMotionY;

    private boolean mBounceHack;

    public PullToRefreshListView(Context context) {
        super(context);
        init(context);
    }

    public PullToRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PullToRefreshListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        // Load all of the animations we need in code rather than through XML
        mFlipAnimation = new RotateAnimation(0, -180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        mFlipAnimation.setInterpolator(new LinearInterpolator());
        mFlipAnimation.setDuration(250);
        mFlipAnimation.setFillAfter(true);
        mReverseFlipAnimation = new RotateAnimation(-180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        mReverseFlipAnimation.setInterpolator(new LinearInterpolator());
        mReverseFlipAnimation.setDuration(250);
        mReverseFlipAnimation.setFillAfter(true);

        mInflater = (LayoutInflater) context.getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);

mRefreshView = (RelativeLayout) mInflater.inflate(
R.layout.pull_to_refresh_header, this, false);
        mRefreshViewText =
            (TextView) mRefreshView.findViewById(R.id.pull_to_refresh_text);
        mRefreshViewImage =
            (ImageView) mRefreshView.findViewById(R.id.pull_to_refresh_image);
        mRefreshViewProgress =
            (ProgressBar) mRefreshView.findViewById(R.id.pull_to_refresh_progress);
        mRefreshViewLastUpdated =
            (TextView) mRefreshView.findViewById(R.id.pull_to_refresh_updated_at);

        mRefreshViewImage.setMinimumHeight(50);
        mRefreshView.setOnClickListener(new OnClickRefreshListener());
        mRefreshOriginalTopPadding = mRefreshView.getPaddingTop();

        mRefreshState = TAP_TO_REFRESH;

        addHeaderView(mRefreshView);

        super.setOnScrollListener(this);

        measureView(mRefreshView);
        mRefreshViewHeight = mRefreshView.getMeasuredHeight();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        setSelection(1);
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);

        setSelection(1);
    }

    /**
     * Set the listener that will receive notifications every time the list
     * scrolls.
     * 
     * @param l The scroll listener. 
     */
    @Override
    public void setOnScrollListener(AbsListView.OnScrollListener l) {
        mOnScrollListener = l;
    }

    /**
     * Register a callback to be invoked when this list should be refreshed.
     * 
     * @param onRefreshListener The callback to run.
     */
    public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
        mOnRefreshListener = onRefreshListener;
    }

    /**
     * Set a text to represent when the list was last updated. 
     * @param lastUpdated Last updated at.
     */
    public void setLastUpdated(CharSequence lastUpdated) {
        if (lastUpdated != null) {
            mRefreshViewLastUpdated.setVisibility(View.VISIBLE);
            mRefreshViewLastUpdated.setText(lastUpdated);
        } else {
            mRefreshViewLastUpdated.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int y = (int) event.getY();
        mBounceHack = false;

        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                if (!isVerticalScrollBarEnabled()) {
                    setVerticalScrollBarEnabled(true);
                }
                if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) {
                    if ((mRefreshView.getBottom() >= mRefreshViewHeight
                            || mRefreshView.getTop() >= 0)
                            && mRefreshState == RELEASE_TO_REFRESH) {
                        // Initiate the refresh
                        mRefreshState = REFRESHING;
                        prepareForRefresh();
                        onRefresh();
                    } else if (mRefreshView.getBottom() < mRefreshViewHeight
                            || mRefreshView.getTop() <= 0) {
                        // Abort refresh and scroll down below the refresh view
                        resetHeader();
                        setSelection(1);
                    }
                }
                break;
            case MotionEvent.ACTION_DOWN:
                mLastMotionY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                applyHeaderPadding(event);
                break;
        }
        return super.onTouchEvent(event);
    }

    private void applyHeaderPadding(MotionEvent ev) {
        // getHistorySize has been available since API 1
        int pointerCount = ev.getHistorySize();

        for (int p = 0; p < pointerCount; p++) {
            if (mRefreshState == RELEASE_TO_REFRESH) {
                if (isVerticalFadingEdgeEnabled()) {
                    setVerticalScrollBarEnabled(false);
                }

                int historicalY = (int) ev.getHistoricalY(p);

                // Calculate the padding to apply, we divide by 1.7 to
                // simulate a more resistant effect during pull.
                int topPadding = (int) (((historicalY - mLastMotionY)
                        - mRefreshViewHeight) / 1.7);

                mRefreshView.setPadding(
                        mRefreshView.getPaddingLeft(),
                        topPadding,
                        mRefreshView.getPaddingRight(),
                        mRefreshView.getPaddingBottom());
            }
        }
    }

    /**
     * Sets the header padding back to original size.
     */
    private void resetHeaderPadding() {
        mRefreshView.setPadding(
                mRefreshView.getPaddingLeft(),
                mRefreshOriginalTopPadding,
                mRefreshView.getPaddingRight(),
                mRefreshView.getPaddingBottom());
    }

    /**
     * Resets the header to the original state.
     */
    private void resetHeader() {
        if (mRefreshState != TAP_TO_REFRESH) {
            mRefreshState = TAP_TO_REFRESH;

            resetHeaderPadding();

            // Set refresh view text to the pull label
            mRefreshViewText.setText(R.string.pull_to_refresh_tap_label);
            // Replace refresh drawable with arrow drawable
            mRefreshViewImage.setImageResource(R.drawable.ic_pulltorefresh_arrow);
            // Clear the full rotation animation
            mRefreshViewImage.clearAnimation();
            // Hide progress bar and arrow.
            mRefreshViewImage.setVisibility(View.GONE);
            mRefreshViewProgress.setVisibility(View.GONE);
        }
    }

    private void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        int childWidthSpec = ViewGroup.getChildMeasureSpec(0,
                0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // When the refresh view is completely visible, change the text to say
        // "Release to refresh..." and flip the arrow drawable.
        if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL
                && mRefreshState != REFRESHING) {
            if (firstVisibleItem == 0) {
                mRefreshViewImage.setVisibility(View.VISIBLE);
                if ((mRefreshView.getBottom() >= mRefreshViewHeight + 20
                        || mRefreshView.getTop() >= 0)
                        && mRefreshState != RELEASE_TO_REFRESH) {
                    mRefreshViewText.setText(R.string.pull_to_refresh_release_label);
                    mRefreshViewImage.clearAnimation();
                    mRefreshViewImage.startAnimation(mFlipAnimation);
                    mRefreshState = RELEASE_TO_REFRESH;
                } else if (mRefreshView.getBottom() < mRefreshViewHeight + 20
                        && mRefreshState != PULL_TO_REFRESH) {
                    mRefreshViewText.setText(R.string.pull_to_refresh_pull_label);
                    if (mRefreshState != TAP_TO_REFRESH) {
                        mRefreshViewImage.clearAnimation();
                        mRefreshViewImage.startAnimation(mReverseFlipAnimation);
                    }
                    mRefreshState = PULL_TO_REFRESH;
                }
            } else {
                mRefreshViewImage.setVisibility(View.GONE);
                resetHeader();
            }
        } else if (mCurrentScrollState == SCROLL_STATE_FLING
                && firstVisibleItem == 0
                && mRefreshState != REFRESHING) {
            setSelection(1);
            mBounceHack = true;
        } else if (mBounceHack && mCurrentScrollState == SCROLL_STATE_FLING) {
            setSelection(1);
        }

        if (mOnScrollListener != null) {
            mOnScrollListener.onScroll(view, firstVisibleItem,
                    visibleItemCount, totalItemCount);
        }
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        mCurrentScrollState = scrollState;

        if (mCurrentScrollState == SCROLL_STATE_IDLE) {
            mBounceHack = false;
        }

        if (mOnScrollListener != null) {
            mOnScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    public void prepareForRefresh() {
        resetHeaderPadding();

        mRefreshViewImage.setVisibility(View.GONE);
        // We need this hack, otherwise it will keep the previous drawable.
        mRefreshViewImage.setImageDrawable(null);
        mRefreshViewProgress.setVisibility(View.VISIBLE);

        // Set refresh view text to the refreshing label
        mRefreshViewText.setText(R.string.pull_to_refresh_refreshing_label);

        mRefreshState = REFRESHING;
    }

    public void onRefresh() {
        Log.d(TAG, "onRefresh");

        if (mOnRefreshListener != null) {
            mOnRefreshListener.onRefresh();
        }
    }

    /**
     * Resets the list to a normal state after a refresh.
     * @param lastUpdated Last updated at.
     */
    public void onRefreshComplete(CharSequence lastUpdated) {
        setLastUpdated(lastUpdated);
        onRefreshComplete();
    }

    /**
     * Resets the list to a normal state after a refresh.
     */
    public void onRefreshComplete() {        
        Log.d(TAG, "onRefreshComplete");

        resetHeader();

        // If refresh view is visible when loading completes, scroll down to
        // the next item.
        if (mRefreshView.getBottom() > 0) {
            invalidateViews();
            setSelection(1);
        }
    }

    /**
     * Invoked when the refresh view is clicked on. This is mainly used when
     * there's only a few items in the list and it's not possible to drag the
     * list.
     */
    private class OnClickRefreshListener implements OnClickListener {

        public void onClick(View v) {
            if (mRefreshState != REFRESHING) {
                prepareForRefresh();
                onRefresh();
            }
        }

    }

    /**
     * Interface definition for a callback to be invoked when list should be
     * refreshed.
     */
    public interface OnRefreshListener {
        /**
         * Called when the list should be refreshed.
         * <p>
         * A call to {@link PullToRefreshListView #onRefreshComplete()} is
         * expected to indicate that the refresh has completed.
         */
        public void onRefresh();
    }
}

Create header layout (pull_to_refresh_header.xml under layout folder)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingTop="10dip"
    android:paddingBottom="15dip"
    android:gravity="center"
        android:id="@+id/pull_to_refresh_header"
    >
    <ProgressBar 
        android:id="@+id/pull_to_refresh_progress"
        android:indeterminate="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="10dip"
        android:visibility="gone"
        android:layout_centerVertical="true"
        style="?android:attr/progressBarStyleSmall"
        />
    <ImageView
        android:id="@+id/pull_to_refresh_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="20dip"
        android:visibility="gone"
        android:layout_gravity="center"
        android:gravity="center"
        android:src="@drawable/ic_pulltorefresh_arrow"
        />
    <TextView
        android:id="@+id/pull_to_refresh_text"
        android:text="@string/pull_to_refresh_tap_label"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold"
        android:paddingTop="5dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/pull_to_refresh_updated_at"
        android:layout_below="@+id/pull_to_refresh_text"
        android:visibility="gone"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:textSize="14sp"
        />
</RelativeLayout>

Create Main layout ( pulltorefresh.xml under layout folder)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

<!--     The PullToRefreshListView replaces a standard ListView widget.
         give the package name where you created the custom PullToreFreshListView
 -->

    <com.androidsurya.customviews.PullToRefreshListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>


Create Main Activity class (MainActivity.java  under com.androidsurya.pulltorefresh pakage)

package com.androidsurya.pulltorefresh;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;

import com.androidsurya.customviews.PullToRefreshListView;
import com.androidsurya.customviews.PullToRefreshListView.OnRefreshListener;

public class MainActivity extends ListActivity {
private List<String> mListItems;

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

// Set a listener to be invoked when the list should be refreshed.
((PullToRefreshListView) getListView())
.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});

mListItems = new ArrayList<String>();
mListItems.addAll(Arrays.asList(mStrings));

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);

setListAdapter(adapter);
}

private class GetDataTask extends AsyncTask<Void, Void, String[]> {

@Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {

}
return mStrings;
}

@Override
protected void onPostExecute(String[] result) {
mListItems.add(0, "Added new item after refresh...");
// Call onRefreshComplete when the list has been refreshed.
((PullToRefreshListView) getListView()).onRefreshComplete();

super.onPostExecute(result);
}
}

private String[] mStrings = { "Andaman and Nicobar Islands",
"Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar",
"Chhattisgarh", "Goa", "Gujarat", "Haryana", "Himachal Pradesh",
"Jammu and Kashmir", "Jharkhand", "Karnataka", "Kerala",
"Madhya Pradesh", "Maharashtra", "Manipur" };
}


Register Activity in Android Manifest file

   <activity
            android:name="com.androidsurya.pulltorefresh.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...