Thursday, 21 February 2013

Android Button with text and image dynamically Part-2

Part-2
In previous blog i add image with text to Button through layout i.e statically.
Now i will show you how to add text with image to Button view dynamically.

Screen Shots:- Before
























Screen Shots 2:--
























Steps:--1

Create an Android project.

layout/activity_main.xml

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:paddingTop="50dp"
        android:text="@string/hello_world"
        android:textSize="16sp" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="10dp" >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonleft"
        android:layout_gravity="center_horizontal"
        android:text="@string/addimagesleft" />
     <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonright"
        android:layout_gravity="center_horizontal"
        android:text="@string/addimagesright" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="10dp" >

        <!-- For Image to the left of the text use android:drawableLeft tag -->

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/butleft"
            android:layout_margin="10dp"
            android:background="@drawable/menu"
            android:drawablePadding="5dp"
            android:text="@string/leftimage" />
        <!-- For Image to the Right of the text use android:drawableRight tag -->

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/butright"
            android:layout_margin="10dp"
            android:background="@drawable/menu"
            android:drawablePadding="5dp"
            android:text="@string/righttimage" />
    </LinearLayout>

  </LinearLayout>



Step 2) src/MainActivity.java

package com.amit.button;

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

public class MainActivity extends Activity {
    private Button setleftBut,setrightbut,buttonwithleft,buttonwithright;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setleftBut=(Button)findViewById(R.id.buttonleft);
        setrightbut=(Button)findViewById(R.id.buttonright);
       
        buttonwithleft=(Button)findViewById(R.id.butleft);
        buttonwithright=(Button)findViewById(R.id.butright);
       
        setleftBut.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                buttonwithleft.setCompoundDrawablesWithIntrinsicBounds(R.drawable.up_arrow, 0,
                        0, 0);
            }
        });
       
        setrightbut.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                buttonwithright.setCompoundDrawablesWithIntrinsicBounds(0, 0,
                        R.drawable.up_arrow, 0);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}


Step:3)
values/strings.xml

     <string name="app_name">ButtonWithImage</string>
    <string name="hello_world">Buttom with Images Dynamically</string>
    <string name="menu_settings">Settings</string>
    <string name="leftimage">LeftImage</string>
    <string name="righttimage">RightImage</string>
     <string name="addimagesleft">Add Image To the Left</string>
    <string name="addimagesright">Add Image To the Right</string>


Download full Source code Click ButtonWithImageDynamically

Wednesday, 20 February 2013

Android Button with text and Images Part-1

In this blog i will show you how to show text with image inside button.
There are two way to achieve this.
1) ImageButton
2) Button

Download Source Code click Here























Today i will use Button to achieve this.


layout/activity_main

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:paddingTop="50dp"
        android:text="@string/hello_world"
        android:textSize="16sp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="10dp" >

        <!-- For Image to the left of the text use android:drawableLeft tag -->

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/menu"
            android:drawableLeft="@drawable/down_arrow"
            android:drawablePadding="5dp"
            android:text="@string/leftimage" />
        <!-- For Image to the Right of the text use android:drawableRight tag -->

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/menu"
            android:drawablePadding="5dp"
            android:drawableRight="@drawable/down_arrow"
            android:text="@string/righttimage" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="10dp" >

        <!-- For Image to the Top of the text use android:drawableTop tag -->

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/menu"
            android:drawablePadding="5dp"
            android:drawableTop="@drawable/down_arrow"
            android:text="@string/toptimage" />
        <!-- For Image to the Bottom of the text use android:drawableBottom tag -->

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:background="@drawable/menu"
            android:drawableBottom="@drawable/down_arrow"
            android:text="@string/bottomtimage" />
    </LinearLayout>

</LinearLayout>

 2) src/com.amit.button

MainActivity.java

package com.amit.button;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

Android PullToRefresh Custom Listview .

In this blog i will show how to implement PullToRefresh Listview in our application.

Screen Shots:-












































These are the following steps to implement PullToRefresh.

Step1)
Create a Android application project.
Create a package named " com.amit.customviews" and create a custom Listview class named as PullToRefreshListView.java

src/com.amit.customviews
 PullToRefreshListView.java

package com.amit.customviews;

import com.amit.pulltorefresh.R;

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.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;


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();
    }
}


Step2 ) in your activity_main.xml
layout/ activity_main.xml

<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.amit.customviews.PullToRefreshListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>


Step 3)
layout/pull_to_refresh_header

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


Step 4) MainActivity.java

package com.amit.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.amit.customviews.PullToRefreshListView;
import com.amit.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(2000);
            } catch (InterruptedException e) {
               
            }
            return mStrings;
        }

        @Override
        protected void onPostExecute(String[] result) {
            mListItems.add(0,"Welcome to Amit blog, Added after refresh...");

            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();

            super.onPostExecute(result);
        }
    }

    private String[] mStrings = {
            "India", "SriLanka",
            "United State", "Australia", "South Korea"};
}

Download Full Source Code click PullToRefreshExample


Android RssFeed with Async Task example

In this blog i will show you how to how to parse Rss Feed. I am going to use Async Task which is very useful to do network operation.

We can do network operation with the help of Thread and Handler  but Async Task is more effective and optimal.

Screen Shots.























Create a project called AndroidRssFeed.
Step1)
Create a Activity named RssReaderActivity.java

package com.amit.rssfeed;

import java.util.List;
import com.amit.Utility.Utility;
import com.amit.adapter.RssReaderListAdapter;
import com.amit.data.AsyncTaskCompletionListener;
import com.amit.data.RssFeedStructure;
import com.amit.network.RssFeedAsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.Toast;

public class RssReaderActivity extends Activity implements AsyncTaskCompletionListener{
    private ListView listview;
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rss_reader);
        listview=(ListView)findViewById(R.id.rssfeed_listview);
        if(Utility.determineConnectivity(this))
        new RssFeedAsyncTask(this).execute(Utility.url);
        else
            Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rss_reader, menu);
        return true;
    }

    @Override
    public void onTaskComplete(List<RssFeedStructure> result) {
        RssReaderListAdapter _adapter= new RssReaderListAdapter(RssReaderActivity.this,
                result);
        listview.setAdapter(_adapter);
    }

}

Step 2)
/layout/rss_reader.xml

<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=".RssReaderActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <ListView
        android:id="@+id/rssfeed_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#5D5C5C"
        android:cacheColorHint="#00000000"
        android:divider="#000000"
        android:dividerHeight="1dip"
        android:transcriptMode="alwaysScroll" >
    </ListView>

</RelativeLayout>

Step 3)
/layout/rssfeedadapter_layout.xml

<?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="wrap_content"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/feed_image"
        android:layout_width="60dip"
        android:layout_height="60dip"
        android:layout_gravity="center_vertical"
        android:background="@drawable/im"
        android:contentDescription="@string/app_name"
        android:padding="7dp" />

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

        <TextView
            android:id="@+id/feed_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="10dip"
            android:paddingLeft="8dip"
            android:paddingRight="8dip"
            android:paddingTop="5dip"
            android:textColor="#FFFFFF" />

        <TextView
            android:id="@+id/feed_updatetime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="3dip"
            android:paddingLeft="8dip"
            android:paddingRight="8dip"
            android:paddingTop="3dip"
            android:textColor="#F6B207"
            android:textSize="10sp" />
    </LinearLayout>

</LinearLayout>


Step 4) Create RssFeedAsyncTask.java class

package com.amit.network;

import java.util.List;
import com.amit.data.AsyncTaskCompletionListener;
import com.amit.data.RssFeedStructure;
import com.amit.data.XmlHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;

public class RssFeedAsyncTask extends
        AsyncTask<String, Void, List<RssFeedStructure>> {
    private ProgressDialog Dialog;
    String response = "";
    List<RssFeedStructure> rssStr;
    Activity _context;
    private AsyncTaskCompletionListener callback;

    public RssFeedAsyncTask(Activity _context) {
        this._context = _context;
        this.callback = (AsyncTaskCompletionListener) _context;
    }

    @Override
    protected void onPreExecute() {
        Dialog = new ProgressDialog(_context);
        Dialog.setMessage("Loading...");
        Dialog.show();

    }

    @Override
    protected List<RssFeedStructure> doInBackground(String... urls) {
        try {
            String feed = urls[0];
            XmlHandler rh = new XmlHandler();
            rssStr = rh.getLatestArticles(feed);
        } catch (Exception e) {
        }
        return rssStr;

    }

    @Override
    protected void onPostExecute(List<RssFeedStructure> result) {
        Dialog.dismiss();
        callback.onTaskComplete(result);

    }

}







Step 5) Create RssReaderListAdapter.java class

package com.amit.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import com.amit.data.RssFeedStructure;
import com.amit.rssfeed.R;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class RssReaderListAdapter extends ArrayAdapter<RssFeedStructure> {
    List<RssFeedStructure> imageAndTexts1 = null;

    public RssReaderListAdapter(Activity activity,
            List<RssFeedStructure> imageAndTexts) {
        super(activity, 0, imageAndTexts);
        imageAndTexts1 = imageAndTexts;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Activity activity = (Activity) getContext();
        LayoutInflater inflater = activity.getLayoutInflater();

        View rowView = inflater.inflate(R.layout.rssfeedadapter_layout, null);
        TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
        TextView timeFeedText = (TextView) rowView
                .findViewById(R.id.feed_updatetime);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
        try {

            Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: "
                    + imageAndTexts1.get(position).getImgLink() + " :: "
                    + imageAndTexts1.get(position).getTitle());
            textView.setText(imageAndTexts1.get(position).getTitle());
            SpannableString content = new SpannableString(imageAndTexts1.get(
                    position).getPubDate());
            content.setSpan(new UnderlineSpan(), 0, 13, 0);

            timeFeedText.setText(content);
            if (imageAndTexts1.get(position).getImgLink() != null) {

                URL feedImage = new URL(imageAndTexts1.get(position)
                        .getImgLink().toString());
                if (!feedImage.toString().equalsIgnoreCase("null")) {
                    HttpURLConnection conn = (HttpURLConnection) feedImage
                            .openConnection();
                    InputStream is = conn.getInputStream();
                    Bitmap img = BitmapFactory.decodeStream(is);
                    imageView.setImageBitmap(img);
                } else {
                    imageView.setBackgroundResource(R.drawable.im);
                }
            }

        } catch (MalformedURLException e) {

        } catch (IOException e) {

        }

        return rowView;

    }

}

Step 5) manifest.xml
Add this permission

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

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


For Download full Source Code click Here

Thursday, 14 February 2013

Android taking Screen shots through code.

In this blog i ll show you how to take screen shots Pragmatically (Through Code) without using DDMS view.



Screen 1) When you click this Munch Screen Button the whole view of this Activity will save into BittmapDrawab

 Screen 2) Final Screen shots

/** layout */
screen_shots.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"
    android:id="@+id/LinearLayout01"
    >
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/munch"
    android:id="@+id/munchscreen"
    />
  <ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/screenshots"
    android:contentDescription="@string/app_name"
    />
 
</LinearLayout>

/** Activity Class */
CaptureScreenShots.java

package com.screen.shots;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class CaptureScreenShots extends Activity {
    LinearLayout L1;
    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_shots);
         L1 = (LinearLayout) findViewById(R.id.LinearLayout01);
            Button but = (Button) findViewById(R.id.munchscreen);
            but.setOnClickListener(new OnClickListener() {
               
                @Override
                public void onClick(View v) {
                    View v1 = L1.getRootView();
                    v1.setDrawingCacheEnabled(true);
                    Bitmap bm = v1.getDrawingCache();
                    BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
                    image = (ImageView) findViewById(R.id.screenshots);
                    image.setBackgroundDrawable(bitmapDrawable);
                }
            });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.screen_shots, menu);
        return true;
    }

}

/** values/strings.xml */

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ScreenShots</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="munch">Munch Screen</string>

</resources>


You can download Source code here