Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Wednesday, 29 January 2014

Android Add and Remove Application Shortcut in Home Screen Example

One of my friend is asking
When i am installing any application from the android market .I seen shortcut of the application in my mobile home screen.

how to create programmatically can u know ?

Based on that request Here i was creating one example how to create shortcut and remove shortcut on home screen.

Android provide intent class com.android.launcher.action.INSTALL_SHORTCUT which can be used to add shortcuts to home screen.

intent class com.android.launcher.permission.UNINSTALL_SHORTCUT which can be used to remove shortcut from home screen.

Here i created Activity with two buttons one for Add shortcut and other one for remove shortcut.And i was using preferences to store state of shortcut (already created or not)

Android Activity(MainActivity.java)

package com.androidsurya.shortcuts;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
Context mContext = MainActivity.this;
SharedPreferences appPreferences;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Preferences to store all ready created or not finding purpose.
appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Add listener to add shortcut button
Button add = (Button) findViewById(R.id.AddShortcut);
add.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (!(appPreferences.getBoolean("isShortcutCreated", false))) {
addShortcut(); // Add shortcut on Home screen

}

}
});

// Add listener to remove shortcut button
Button remove = (Button) findViewById(R.id.RemoveShortcut);
remove.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
removeShortcut(); // Remove shortcut from Home screen
}
});
}

private void addShortcut() {
// Adding shortcut for MainActivity
// on Home screen
Intent shortcutIntent = new Intent(getApplicationContext(),
MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Example");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(
getApplicationContext(), R.drawable.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
SharedPreferences.Editor editor = appPreferences.edit();
editor.putBoolean("isShortcutCreated", true);
editor.commit();
}

private void removeShortcut() {
// Deleting shortcut for MainActivity
// on Home screen
Intent shortcutIntent = new Intent(getApplicationContext(),
MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Example");
addIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
SharedPreferences.Editor editor = appPreferences.edit();
editor.putBoolean("isShortcutCreated", false);
editor.commit();
}

}

Android UI 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" >

    <Button
        android:id="@+id/AddShortcut"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add Shortcut" />

    <Button
        android:id="@+id/RemoveShortcut"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Remove Shortcut" />

</LinearLayout>

Note: 
 Don't Forget Register this Below permissions  In Manifest File 

<uses-permission
         android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
    <uses-permission
         android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />

Output Screenshot:






   































Tags : Android application,app shortcut in homescreen,android homescreen with application shortcut,application shortcut,remove shortcut from home screen,how to add shortcut of application in home screen.

Thursday, 17 October 2013

List of open source Game Engines for Android(Android Game Development)

Here below is list of Game Engine used in Android Game Development

  • Open Source Android Apps for Developers: jMonkeyEngine (Java Based 3D Game Engine)
  • Open Source Android Apps for Developers: Android-2D-Engine (Android Game)
  • Open Source Android Apps for Developers: YoghurtGum (Android Game Engine)
  • Open Source Android Apps for Developers: Catcake (Android Game Engine)
  • Open Source Android Apps for Developers: jPCT-AE (Android Game 3D Engine)
  • Open Source Android Apps for Developers: Dwarf-fw (Android 3D Framework)
  • Open Source Android Apps for Developers: Mages (Android Game Engine)
  • Open Source Android Apps for Developers: AndEngine (Android Game Engine)
  • Open Source Android Apps for Developers: Angle (Android Game Engine)

Tuesday, 1 October 2013

Android GridLayout Example (New Feature in 4.0)

Here The Below Example shows How to create GridLayout in Android ?

GridLayout induced in Android 4.0 as New Feature.

LinearLayout and RelativeLayout are the most common layouts used in user
interface design in Android. For simple user interfaces they are a good choice but
when the user interface gets complicated, the use of nested LinearLayout tends
to increase. Nested layouts (of any type) can hurt performance, and furthermore
nested LinearLayout deeper than 10 may cause a crash in your application.
Thus, you should either avoid using too many nested LinearLayout blocks or
you should use RelativeLayout in order to decrease nested LinearLayout blocks.
Another drawback of these layouts for complicated user interfaces is the difficulty
in readability. It is difficult to maintain nested LinearLayout or RelativeLayout
layouts that have many views. It is a good choice to use GridLayout in these
cases. Too many nested LinearLayouts could be avoided by using GridLayout.
Furthermore, it is much easier to maintain GridLayout. Many of the user interfaces
that use LinearLayout, RelativeLayout, or TableLayout can be converted to
GridLayout where GridLayout will provide performance enhancements. One of
the major advantages of GridLayout over other layouts is that you can control the
alignment of a view in both horizontal and vertical axes.

Example GridLayout:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="3"
    android:rowCount="3" >
    <Button android:text="1,1" />
    <Button android:text="1,2" />
    <Button android:text="1,3" />
    <Button android:text="2,1" />
    <Button android:text="2,2" />
    <Button android:text="2,3" />
    <Button android:text="3,1" />
    <Button android:text="3,2" />
    <Button android:text="3,3" />
</GridLayout>

Output Screen:








Monday, 30 September 2013

How to connect the micromax Phone to the eclipse?

Hi friends to detect micromax mobile to the eclipse for Development purpose .Just download this below Driver and install .Then you can see Your Device in Eclipse Devices List.

Note: Don't forget to enable USB Debug mode in Developer Options in Settings.

Click on Globe to Download Driver.

If your Unable to find Developer option in your micromax mobile just follow below post for enable for find Developer option in your mobile.


Tuesday, 10 September 2013

New Features For Android Application Development Explanation with Source

This below  book is a practical and hands-on guide for developing Android applications
using new features of Android Ice Cream Sandwich (Android 4.0), with a step-by-step
approach and clearly explained sample codes. You will learn the new APIs in Android
4.0 with these sample codes.

This Book covers these Below points.

Action Bar
New Layout(GridLayout)
Social APIs
Calendar APIs
Fragments
Supporting Different Screen Sizes
Android Compatibility Package
New Connectivity APIs





Friday, 9 August 2013

Monday, 28 January 2013

External font Across the Android Application

Sometimes in Android app we may need to maintain same font across application. At point of time previews post is not sufficient.

Here below Example shows how to use External font across the application.

Here First I have downloaded ".ttf” file from google. Created a new folder “font” in assets folder and paste your recently downloaded font file.




















we can do that by just extending your class from android TextView.

Below code is to my customized TextView class(OwnFontTextView.java)

package com.androidsurya.androidexternalfontexample;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class OwnFontTextView extends TextView {
    public OwnFontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setFont();
    }

    public OwnFontTextView(Context context, AttributeSet attrs) {
        // call the constructor which has the complete definition
        this(context, attrs, 0);
    }

    public OwnFontTextView(Context context) {
        super(context);
    }

    public void setFont() {
        String ttf_fontPath = "fonts/TIMES_SQ.TTF";
        Typeface font = Typeface.createFromAsset(getContext().getAssets(),
                ttf_fontPath);
        setTypeface(font);
    }
}

In our Layout insted of declare <TextView/> tag we just specify <com.androidsurya.androidexternalfontexample.OwnFontTextView/>
in any were in our application.


 <com.androidsurya.androidexternalfontexample.OwnFontTextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Hello Android"
        android:textColor="#65E561"
        android:textSize="45dp" />

Then external font will be applied to Text.

Screenshot























Wednesday, 16 January 2013

Diffrence between managedQuery() vs context.getContentResolver.query() in Android

In android managedQuery() will use ContentResolver's query(). The difference is
that with managedQuery() the activity will keep a reference to your
Cursor and close it whenever needed (in onDestroy() for instance.) If
you do query() yourself, you *will* have to manage the Cursor as a
sensitive resource. If you forget, for instance, to close() it in
onDestroy(), you will leak underlying resources (logcat will warn you
about it.)

Thursday, 8 November 2012

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>


Wednesday, 31 October 2012

How to parse xml file in Assert folder in Android using Dom Parser

This below example parse xml file which in assert folder of our project.
This file contains employee details this example parse xml file data and set to textview.

Data file (employeesdetails.xml) create this file assert folder .
In this example we read this file

<?xml version="1.0"?>
<employee_list>
<employee>
    <employee_id>1001</employee_id>
<employee_name>Android </employee_name>
<employee_salary>50000</employee_salary>
</employee>
<employee>
    <employee_id>1002</employee_id>
<employee_name>Surya </employee_name>
<employee_salary>60000</employee_salary>
</employee>
<employee>
    <employee_id>1003</employee_id>
<employee_name>Narayana </employee_name>
<employee_salary>40000</employee_salary>
</employee>
</employee_list>

Android UI 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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="86dp"
        android:layout_marginTop="77dp"
        android:text="TextView" />

</RelativeLayout>

Android Activity (MainActivity.java)

package com.androidsurya.xmlparsing;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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

public class MainActivity extends Activity {
TextView textView;
InputStream inputStream;
DocumentBuilderFactory dbFactory;
DocumentBuilder docBuilder;
Document doc;
Element element;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
try {
inputStream = getAssets().open("employeesdetails.xml");

dbFactory = DocumentBuilderFactory.newInstance();
docBuilder = dbFactory.newDocumentBuilder();
doc = docBuilder.parse(inputStream);

element = doc.getDocumentElement();
element.normalize();

NodeList nList = doc.getElementsByTagName("employee");
for (int i = 0; i < nList.getLength(); i++) {

Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
textView.setText(textView.getText() + "\nEmployee Id : "
+ getValuefromTagName("employee_id", element2) + "\n");
textView.setText(textView.getText() + "Employee Name : "
+ getValuefromTagName("employee_name", element2) + "\n");
textView.setText(textView.getText() + "Employee Salary: "
+ getValuefromTagName("employee_salary", element2) + "\n");
textView.setText(textView.getText()
+ "===========================");
}
}
} catch (Exception e) {
e.printStackTrace();
}

}

private static String getValuefromTagName(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0)
.getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}

}

Register Activity in Android Manifest file

 <activity
            android:name="com.androidsurya.xmlparsing.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>

Output Screenshot





















Tuesday, 18 September 2012

Android Text Alignment on Button Example

Here I attached below code to Align Button Text in Different ways.

Android Provide one Good Attribute i.e android:gravity in Button.


Simply just copy the below code in your layout 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"
    tools:ignore="HardcodedText" >

    <Button
        android:id="@+id/left"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="left|center_vertical"
        android:text="Left Center Text" />

    <Button
        android:id="@+id/right"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right|center_vertical"
        android:text="Right Center Text" />

    <Button
        android:id="@+id/top_center"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top|center"
        android:text="Top Center Text" />

    <Button
        android:id="@+id/bottom_center"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom|center"
        android:text="Bottom Center Text" />

    <Button
        android:id="@+id/top"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top|left"
        android:text="Top Left Text" />

    <Button
        android:id="@+id/top_right"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top|right"
        android:text="Top Right Text" />

    <Button
        android:id="@+id/bottom_left"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom|left"
        android:text="Bottom Left Text" />

    <Button
        android:id="@+id/bottom_right"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom|right"
        android:text="Bottom Right Text" />

</LinearLayout>

Screenshot
























Thursday, 23 August 2012

GridView Example in Android

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a Adapter.


Here The below Example Project shows GridView With A to Z TextView Elements.
UI Layout(grid_view_example.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=".GridViewExample" >

    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:numColumns="3" >
    </GridView>

</RelativeLayout>

Android Activity Class(GridViewExample.java)

package com.androidsurya.androidgridviewexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class GridViewExample extends Activity {

    static final String[] numbers = new String[] { "A", "B", "C", "D", "E",
            "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z" };
    GridView gridView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_view_example);
        gridView = (GridView) findViewById(R.id.gridView);

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

        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                // TODO Auto-generated method stub

                Toast.makeText(getApplicationContext(),
                        "Selected: " + ((TextView) v).getText(),
                        Toast.LENGTH_SHORT).show();

            }
        });
    }

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

}

Register Activity in AndroidManifest file

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

Output Screenshot








For more information about GridView :- Android Developers site

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