Sample Order Page Example in Android Programming

This example shows how to create a layout to place an order for a company and send it.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it SampleOrderPageExample.

2.) Write following into main.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">

        <TableLayout android:id="@+id/TableLayout01"
                android:layout_width="wrap_content" android:layout_height="wrap_content">

                <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                        <TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
                                android:layout_height="wrap_content" android:text="BP"></TextView>
                        <EditText android:id="@+id/EditText01"
                                android:layout_width="wrap_content" android:layout_height="wrap_content"
                                android:minWidth="200px" ></EditText>

</TableRow>
                <TableRow android:id="@+id/TableRow02" android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                        <TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
                                android:layout_height="wrap_content" android:text="Type"></TextView>

                        <Spinner android:id="@+id/Spinner01" android:layout_width="wrap_content"
                                android:layout_height="wrap_content" android:entries="@array/ordertypes"></Spinner>
                </TableRow>

                <TableRow android:id="@+id/TableRow05" android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                        <TextView android:id="@+id/TextView04" android:layout_width="wrap_content"
                                android:layout_height="wrap_content" android:text="Quantity"></TextView>
                        <EditText android:id="@+id/EditText02"
                                android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="numberSigned|numberDecimal"></EditText>

                        <Spinner android:id="@+id/Spinner02" android:layout_width="wrap_content"
                                android:layout_height="wrap_content" android:entries="@array/quantity"></Spinner>
                </TableRow>
                <TableRow android:id="@+id/TableRow04" android:layout_width="wrap_content"
                        android:layout_height="wrap_content">

                </TableRow>

        </TableLayout>
        <DatePicker android:id="@+id/DatePicker01"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></DatePicker>
        <Button android:id="@+id/Button01" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="Send" android:width="120px">

        </Button>

<RatingBar android:id="@+id/RatingBar01" android:layout_width="wrap_content" android:layout_height="wrap_content"></RatingBar>
</LinearLayout>

3.) Create and write following into res/values/quantity.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="quantity"><item>TON</item>
<item>KG</item>
</string-array>
</resources>

4.) Create and write following into res/values/ordertypes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="ordertypes"><item>Immediate Order</item>
<item>Slow Order</item>
<item>Normal Order</item>
</string-array>
</resources>

5.) Run for output.

Steps:

1.) Create a project named SampleOrderPageExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: SampleOrderPageExample
Package Name: com. example. SampleOrderPageExample
Activity Name: SampleOrderPageExample
Min SDK Version: 8

2.) Open SampleOrderPageExample.java file and write following code there:

package com.example.SampleOrderPageExample;

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

public class SampleOrderPageExample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button =(Button) findViewById(R.id.Button01);
        button.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher));
        button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                                Toast.makeText(getBaseContext(), "Sending Order!!! Please wait…", 5000).show();
                        }
                });
    }
}

3.) Compile and build the project.

Output

Posted in Android App programming, Android Development, Learn Android Programming | Tagged , , , , , | Leave a comment

Compass Example in Android Programming

This example explains how you can create compass into your application and how to use sensor events.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it CompassExample.

2.) Create and write following into GraphicsActivity.java:

package com.example.CompassExample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

class GraphicsActivity extends Activity {
    private static final boolean TEST_PICTURE = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setContentView(View view) {
        if (TEST_PICTURE) {
            ViewGroup vg = new PictureLayout(this);
            vg.addView(view);
            view = vg;
        }

        super.setContentView(view);
    }
}

3.) Write following into PictureLayout.java:

package com.example.CompassExample;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

public class PictureLayout extends ViewGroup {
    private final Picture mPicture = new Picture();

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

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

    @Override
    public void addView(View child) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child);
    }

    @Override
    public void addView(View child, int index) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index);
    }

    @Override
    public void addView(View child, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, params);
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index, params);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }

        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();

        Drawable drawable = getBackground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
                resolveSize(maxHeight, heightMeasureSpec));
    }

    private void drawPict(Canvas canvas, int x, int y, int w, int h,
                          float sx, float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();

        int x = getWidth()/2;
        int y = getHeight()/2;

        if (false) {
            canvas.drawPicture(mPicture);
        } else {
            drawPict(canvas, 0, 0, x, y,  1,  1);
            drawPict(canvas, x, 0, x, y, -1,  1);
            drawPict(canvas, 0, y, x, y,  1, -1);
            drawPict(canvas, x, y, x, y, -1, -1);
        }
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childLeft = getPaddingLeft();
                final int childTop = getPaddingTop();
                child.layout(childLeft, childTop,
                        childLeft + child.getMeasuredWidth(),
                        childTop + child.getMeasuredHeight());

            }
        }
    }
}

4.) Run for output.

Steps:

1.) Create a project named CompassExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: CompassExample
Package Name: com. example. CompassExample
Activity Name: CompassExampleActivity
Min SDK Version: 14

2.) Open CompassExampleActivity.java file and write following code there:

package com.example.CompassExample;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class CompassExampleActivity extends GraphicsActivity {

    private static final String TAG = "Compass";

    private SensorManager mSensorManager;
    private Sensor mSensor;
    private SampleView mView;
    private float[] mValues;

    private final SensorEventListener mListener = new SensorEventListener() {
        public void onSensorChanged(SensorEvent event) {
            if (false) Log.d(TAG,
                    "sensorChanged (" + event.values[0] + ", " + event.values[1] + ", " + event.values[2] + ")");
            mValues = event.values;
            if (mView != null) {
                mView.invalidate();
            }
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        mView = new SampleView(this);
        setContentView(mView);
    }

    @Override
    protected void onResume()
    {
        if (false) Log.d(TAG, "onResume");
        super.onResume();

        mSensorManager.registerListener(mListener, mSensor,
                SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onStop()
    {
        if (false) Log.d(TAG, "onStop");
        mSensorManager.unregisterListener(mListener);
        super.onStop();
    }

    private class SampleView extends View {
        private Paint   mPaint = new Paint();
        private Path    mPath = new Path();
        private boolean mAnimate;

        public SampleView(Context context) {
            super(context);

            // Construct a wedge-shaped path
            mPath.moveTo(0, -50);
            mPath.lineTo(-20, 60);
            mPath.lineTo(0, 50);
            mPath.lineTo(20, 60);
            mPath.close();
        }

        @Override protected void onDraw(Canvas canvas) {
            Paint paint = mPaint;

            canvas.drawColor(Color.WHITE);

            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.FILL);

            int w = canvas.getWidth();
            int h = canvas.getHeight();
            int cx = w / 2;
            int cy = h / 2;

            canvas.translate(cx, cy);
            if (mValues != null) {
                canvas.rotate(-mValues[0]);
            }
            canvas.drawPath(mPath, mPaint);
        }

        @Override
        protected void onAttachedToWindow() {
            mAnimate = true;
            if (false) Log.d(TAG, "onAttachedToWindow. mAnimate=" + mAnimate);
            super.onAttachedToWindow();
        }

        @Override
        protected void onDetachedFromWindow() {
            mAnimate = false;
            if (false) Log.d(TAG, "onDetachedFromWindow. mAnimate=" + mAnimate);
            super.onDetachedFromWindow();
        }
    }
}

3.) Compile and build the project

Output

Posted in Android Application Development, Android Game Programming, Free Android Tutorials | Tagged , , , , | Leave a comment

Image Gallery Example in Android

This example shows how create ImageGallery in android.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it ImageGalleryExample.

2.) Add some sample .png image files to res/drawables folder.

3.) Write following into main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   
    <ImageSwitcher android:id="@+id/switcher"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_alignParentTop="true"
       android:layout_alignParentLeft="true"
   />
   
    <Gallery android:id="@+id/gallery"
       android:background="#55000000"
       android:layout_width="match_parent"
       android:layout_height="60dp"
       android:layout_alignParentBottom="true"
       android:layout_alignParentLeft="true"
       
       android:gravity="center_vertical"
       android:spacing="16dp"
   />

</RelativeLayout>

4.) Run for output.

Steps:

1.) Create a project named ImageGalleryExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: ImageGalleryExample
Package Name: com. example. ImageGalleryExample
Activity Name: ImageGalleryExample
Min SDK Version: 14

2.) Open ImageGalleryExample.java file and write following code there:

package com.example.ImageGalleryExample;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class ImageGalleryExample extends Activity implements
        AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main);

        mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));

        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
        g.setOnItemSelectedListener(this);
    }

    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
        mSwitcher.setImageResource(mImageIds[position]);
    }

    public void onNothingSelected(AdapterView<?> parent) {
    }

    public View makeView() {
        ImageView i = new ImageView(this);
        i.setBackgroundColor(0xFF000000);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        return i;
    }

    private ImageSwitcher mSwitcher;

    public class ImageAdapter extends BaseAdapter {
        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);

            i.setImageResource(mThumbIds[position]);
            i.setAdjustViewBounds(true);
            i.setLayoutParams(new Gallery.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            i.setBackgroundResource(R.drawable.picture_frame);
            return i;
        }

        private Context mContext;

    }

    private Integer[] mThumbIds = {
            R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
            R.drawable.sample_thumb_2, R.drawable.sample_thumb_3};

    private Integer[] mImageIds = {
            R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
            R.drawable.sample_3};

}

3.) Compile and build the project.

Output

Posted in Android Development, Android programming, Free Android Tutorials | Tagged , , , | Leave a comment

Live Wallpaper in Android

This example explains how to create and set live wallpaper in android.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it LiveWallpaper.

2.) Write following into manifest file:

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.example.LiveWallpaper" android:versionCode="1"  
   android:versionName="1.0">  
    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">  
 
 
        <service android:name="MyWallpaperService" android:enabled="true"  
           android:permission="android.permission.BIND_WALLPAPER" android:label="Wallpaper Example ">  
            <intent-filter>  
                <action android:name="android.service.wallpaper.WallpaperService"></action>  
            </intent-filter>  
            <meta-data android:name="android.service.wallpaper"  
               android:resource="@xml/mywallpaper"></meta-data>  
        </service>  
        <activity android:label="@string/app_name" android:name=".LiveWallpaperActivity"  
           android:theme="@android:style/Theme.Light.WallpaperSettings"  
           android:exported="true">  
        </activity>  
    </application>  
    <uses-sdk android:minSdkVersion="10" />  
    <uses-feature android:name="android.software.live_wallpaper"  
       android:required="true"></uses-feature>  
 
</manifest>

3.) Create “xml” folder into res directory and create and write following into mywallpaper.xml:

<?xml version="1.0" encoding="UTF-8"?>  
<wallpaper  
   android:settingsActivity="de.vogella.android.wallpaper.MyPreferencesActivity"  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:description="@string/wallpaper_description"  
   android:thumbnail="@drawable/ic_launcher" />

4.) Create and write following into prefs.xml:

<?xml version="1.0" encoding="utf-8"?>  
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">  
    <CheckBoxPreference android:key="touch"  
       android:title="Enable Touch"></CheckBoxPreference>  
    <EditTextPreference android:key="numberOfCircles"  
       android:title="Number of Circles"></EditTextPreference>  
</PreferenceScreen>

5.) Create and write following code into src/MyPoints.java:

package com.example.LiveWallpaper;

public class MyPoint {  
    public String text;  
    public float x;  
    public float y;  
 
    public MyPoint(String text, float x, float y) {  
        this.text = text;  
        this.x = x;  
        this.y = y;  
    }  
 
}

6.) Create a service class to make the wallpaper application run from background. Write following into MyWallpaperService.java:

package com.example.LiveWallpaper;

import java.util.ArrayList;  
import java.util.List;  
 
import android.content.SharedPreferences;  
import android.graphics.Canvas;  
import android.graphics.Color;  
import android.graphics.Paint;  
import android.os.Handler;  
import android.preference.PreferenceManager;  
import android.service.wallpaper.WallpaperService;  
import android.view.MotionEvent;  
import android.view.SurfaceHolder;  
 
public class MyWallpaperService extends WallpaperService {  
 
    @Override  
    public Engine onCreateEngine() {  
        return new MyWallpaperEngine();  
    }  
 
    private class MyWallpaperEngine extends Engine {  
        private final Handler handler = new Handler();  
        private final Runnable drawRunner = new Runnable() {  
            @Override  
            public void run() {  
                draw();  
            }  
 
        };  
        private List<MyPoint> circles;  
        private Paint paint = new Paint();  
        private int width;  
        int height;  
        private boolean visible = true;  
        private int maxNumber;  
        private boolean touchEnabled;  
 
        public MyWallpaperEngine() {  
            SharedPreferences prefs = PreferenceManager  
                    .getDefaultSharedPreferences(MyWallpaperService.this);  
            maxNumber = Integer  
                    .valueOf(prefs.getString("numberOfCircles", "10"));  
            touchEnabled = prefs.getBoolean("touch", false);  
            circles = new ArrayList<MyPoint>();  
            paint.setAntiAlias(true);
            paint.setColor(Color.GREEN);  
            paint.setStyle(Paint.Style.STROKE);  
            paint.setStrokeJoin(Paint.Join.ROUND);  
            paint.setStrokeWidth(10f);  
            handler.post(drawRunner);  
        }  
 
        @Override  
        public void onVisibilityChanged(boolean visible) {  
            this.visible = visible;  
            if (visible) {  
                handler.post(drawRunner);  
            } else {  
                handler.removeCallbacks(drawRunner);  
            }  
        }  
 
        @Override  
        public void onSurfaceDestroyed(SurfaceHolder holder) {  
            super.onSurfaceDestroyed(holder);  
            this.visible = false;  
            handler.removeCallbacks(drawRunner);  
        }  
 
        @Override  
        public void onSurfaceChanged(SurfaceHolder holder, int format,  
                int width, int height) {  
            this.width = width;  
            this.height = height;  
            super.onSurfaceChanged(holder, format, width, height);  
        }  
 
        @Override  
        public void onTouchEvent(MotionEvent event) {  
            if (touchEnabled) {  
 
                float x = event.getX();  
                float y = event.getY();  
                SurfaceHolder holder = getSurfaceHolder();  
                Canvas canvas = null;  
                try {  
                    canvas = holder.lockCanvas();  
                    if (canvas != null) {  
                        canvas.drawColor(Color.BLACK);  
                        circles.clear();  
                        circles.add(new MyPoint(  
                                String.valueOf(circles.size() + 1), x, y));  
                        drawCircles(canvas, circles);  
 
                    }  
                } finally {  
                    if (canvas != null)  
                        holder.unlockCanvasAndPost(canvas);  
                }  
                super.onTouchEvent(event);  
            }  
        }  
 
        private void draw() {  
            SurfaceHolder holder = getSurfaceHolder();  
            Canvas canvas = null;  
            try {  
                canvas = holder.lockCanvas();  
                if (canvas != null) {  
                    if (circles.size() >= maxNumber) {  
                        circles.clear();  
                    }  
                    int x = (int) (width * Math.random());  
                    int y = (int) (height * Math.random());  
                    circles.add(new MyPoint(String.valueOf(circles.size() + 1),  
                            x, y));  
                    drawCircles(canvas, circles);  
                }  
            } finally {  
                if (canvas != null)  
                    holder.unlockCanvasAndPost(canvas);  
            }  
            handler.removeCallbacks(drawRunner);  
            if (visible) {  
                handler.postDelayed(drawRunner, 5000);  
            }  
        }  
 
        // Surface view requires that all elements are drawn completely  
        private void drawCircles(Canvas canvas, List<MyPoint> circles) {  
            canvas.drawColor(Color.BLACK);  
            for (MyPoint point : circles) {  
                canvas.drawCircle(point.x, point.y, 20.0f, paint);  
            }  
        }  
    }  
 
}

7.) Run for output.

Steps:

1.) Create a project named LiveWallpaper and set the information as stated in the image.

Build Target: Android 4.0
Application Name: LiveWallpaper
Package Name: com. example. LiveWallpaper
Activity Name: LiveWallpaperActivity
Min SDK Version: 14

2.) Open LiveWallpaperActivity.java file and write following code there:

package com.example.LiveWallpaper;

import android.os.Bundle;  
import android.preference.Preference;  
import android.preference.Preference.OnPreferenceChangeListener;  
import android.preference.PreferenceActivity;  
import android.widget.Toast;  
 
public class LiveWallpaperActivity extends PreferenceActivity {  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        addPreferencesFromResource(R.xml.prefs);  
 
        // We want to add a validator to the number of circles so that it only  
        // accepts numbers  
        Preference circlePreference = getPreferenceScreen().findPreference(  
                "numberOfCircles");  
 
        // Add the validator  
        circlePreference.setOnPreferenceChangeListener(numberCheckListener);  
    }  
 
        Preference.OnPreferenceChangeListener numberCheckListener = new OnPreferenceChangeListener() {  
 
        @Override  
        public boolean onPreferenceChange(Preference preference, Object newValue) {  
            // Check that the string is an integer  
            if (newValue != null && newValue.toString().length() > 0  
                    && newValue.toString().matches("\\d*")) {  
                return true;  
            }  
            // If now create a message to the user  
            Toast.makeText(LiveWallpaperActivity.this, "Invalid Input",  
                    Toast.LENGTH_SHORT).show();  
            return false;  
        }  
    };  
}

3.) Compile and build the project.

Output

Posted in Android App programming, Android programming, Android Tutorials, Free Android Tutorials | Tagged , , , , | Leave a comment

Layout Animation in Android

This example explains about the default layout animation in android.

Algorithm:

1.)  Create a new project by File-> New -> Android Project name it LayoutAnimation.

2.)  Write following into main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   >
    <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Add Button"
       android:id="@+id/addNewButton"
       />
    <GridLayout
       android:columnCount="4"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/gridContainer"
       android:animateLayoutChanges="true"
       />
</LinearLayout>

3.)  Run for output.

Steps:

1.) Create a project named LayoutAnimation and set the information as stated in the image.

Build Target: Android 4.0
Application Name: LayoutAnimation
Package Name: com. example. LayoutAnimation
Activity Name: LayoutAnimationActivity
Min SDK Version: 14

2.) Open LayoutAnimationActivity.java file and write following code there:

package com.example.layoutanimation;

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

public class LayoutAnimationActivity extends Activity {
        private int numButtons = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final GridLayout gridContainer = (GridLayout) findViewById(R.id.gridContainer);

        Button addButton = (Button) findViewById(R.id.addNewButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Button newButton = new Button(LayoutAnimationActivity.this);
                newButton.setText(String.valueOf(numButtons++));
                newButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        gridContainer.removeView(v);
                    }
                });
                gridContainer.addView(newButton, Math.min(1, gridContainer.getChildCount()));
            }
        });
    }

}

3.) Compile and build the project.

Output

Posted in Android App programming, Android programming, Free Android Tutorials, Learn Android Programming | Tagged , , , , , | Leave a comment

Calendar Application

This example explains how to call and use system calendar into your application.

Algorithm:

1.)   Create a new project by File-> New -> Android Project name it CalendarApplication.

2.)   Write following into main.xml file:

&lt;?xml version=<em>"1.0"</em> encoding=<em>"utf-8"</em>?&gt;

&lt;LinearLayout xmlns:android=<em>"http://schemas.android.com/apk/res/android"</em>

android:layout_width=<em>"fill_parent"</em>

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

android:orientation=<em>"vertical"</em> &gt;

&lt;Button

android:id=<em>"@+id/button1"</em>

android:layout_width=<em>"wrap_content"</em>

android:layout_height=<em>"wrap_content"</em>

android:onClick=<em>"onClick"</em>

android:text=<em>"Create Event"</em> /&gt;

&lt;Button

android:id=<em>"@+id/button2"</em>

android:layout_width=<em>"wrap_content"</em>

android:layout_height=<em>"wrap_content"</em>

android:onClick=<em>"queryCalendar"</em>

android:text=<em>"Query Calendar"</em> /&gt;

&lt;/LinearLayout&gt;

3.)   Put INTERNET permission to manifest file:

<uses-permission

android:name=“android.permission.READ_CALENDAR”>

</uses-permission>

<uses-permission

android:name=“android.permission.WRITE_CALENDAR”>

</uses-permission>

4.)   Run for output.

Steps:

1.) Create a project named CalendarApplication and set the information as stated in the image.

Build Target: Android 4.0

Application Name: CalendarApplication

Package Name: com. example. CalendarApplication

Activity Name: CalendarApplicationActivity

Min SDK Version: 14

2.) Open CalendarApplicationActivity.java file and write following code there:

<strong>package</strong> com.example.CalendarApplication;

<strong>import</strong> java.util.GregorianCalendar;

<strong>import</strong> android.app.Activity;

<strong>import</strong> android.content.ContentResolver;

<strong>import</strong> android.content.Intent;

<strong>import</strong> android.database.Cursor;

<strong>import</strong> android.net.Uri;

<strong>import</strong> android.os.Bundle;

<strong>import</strong> android.provider.CalendarContract;

<strong>import</strong> android.provider.CalendarContract.Calendars;

<strong>import</strong> android.provider.CalendarContract.Events;

<strong>import</strong> android.view.View;

<strong>import</strong> android.widget.Toast;

<strong>public</strong> <strong>class</strong> CalendarApplicationActivity  <strong>extends</strong> Activity {

<strong>public</strong> <strong>static</strong> <strong>final</strong> String[] <em>EVENT_PROJECTION</em> = <strong>new</strong> String[] {

Calendars.<em>_ID</em>, // 0

Calendars.<em>ACCOUNT_NAME</em>, // 1

Calendars.<em>CALENDAR_DISPLAY_NAME</em> // 2

};

<strong>private</strong> <strong>static</strong> <strong>final</strong> <strong>int</strong> <em>PROJECTION_DISPLAY_NAME_INDEX</em> = 2;

@Override

<strong>public</strong> <strong>void</strong> onCreate(Bundle savedInstanceState) {

<strong>super</strong>.onCreate(savedInstanceState);

setContentView(R.layout.<em>main</em>);

}

<strong>public</strong> <strong>void</strong> onClick(View view) {

Intent intent = <strong>new</strong> Intent(Intent.<em>ACTION_INSERT</em>);

intent.setType("vnd.android.cursor.item/event");

intent.putExtra(Events.<em>TITLE</em>, "Learn Android");

intent.putExtra(Events.<em>EVENT_LOCATION</em>, "Home suit home");

intent.putExtra(Events.<em>DESCRIPTION</em>, "Download Examples");

GregorianCalendar calDate = <strong>new</strong> GregorianCalendar(2012, 10, 02);

intent.putExtra(CalendarContract.<em>EXTRA_EVENT_BEGIN_TIME</em>,

calDate.getTimeInMillis());

intent.putExtra(CalendarContract.<em>EXTRA_EVENT_END_TIME</em>,

calDate.getTimeInMillis());

intent.putExtra(CalendarContract.<em>EXTRA_EVENT_ALL_DAY</em>, <strong>true</strong>);

intent.putExtra(Events.<em>RRULE</em>,

"FREQ=WEEKLY;COUNT=11;WKST=SU;BYDAY=TU,TH");

intent.putExtra(Events.<em>ACCESS_LEVEL</em>, Events.<em>ACCESS_PRIVATE</em>);

intent.putExtra(Events.<em>AVAILABILITY</em>, Events.<em>AVAILABILITY_BUSY</em>);

startActivity(intent);

}

<strong>public</strong> <strong>void</strong> queryCalendar(View view) {

Cursor cur = <strong>null</strong>;

ContentResolver cr = getContentResolver();

Uri uri = Calendars.<em>CONTENT_URI</em>;

String selection = "((" + Calendars.<em>ACCOUNT_NAME</em> + " = ?) AND ("

+ Calendars.<em>ACCOUNT_TYPE</em> + " = ?))";

String[] selectionArgs = <strong>new</strong> String[] { "Lars.Vogel@gmail.com",

"com.google" };

cur = cr.query(uri, <em>EVENT_PROJECTION</em>, selection, selectionArgs, <strong>null</strong>);

<strong>while</strong> (cur.moveToNext()) {

String displayName = <strong>null</strong>;

displayName = cur.getString(<em>PROJECTION_DISPLAY_NAME_INDEX</em>);

Toast.<em>makeText</em>(<strong>this</strong>, "Calendar " + displayName, Toast.<em>LENGTH_SHORT</em>)

.show();

}

}

}

3.) Compile and build the project.

Output

4.) If your phone doesn’t have any default calendar installed you will see the screen as below. Follow the instructions and see your calendar.

Posted in Android Application Development | Tagged , , , | Leave a comment

Google Android 4.0: Ice Cream Sandwich Comes With Some Amazing Features

Google android currently is a most well-known stand, as per varied survey company this Android tutorialsandroid mobile operating system turned into most common than apple iPhone smart phone. And still in frequently developing and that makes it different and that is the major valid reason for turning into so much widely used in short period of time. Google has launched android 3. 1, 3. 0, and 3. 2 honeycomb and even the gingerbread for smart phone. Last year company has declared about android 4. 0 that is also identified as ice cream sandwich, by that android has shake the complete smart phone market and people who are eager of utilizing smart phone they will definitely wait for this completely unique product.

The essential thing is after the announcement of this news is spreading like a wind all over the internet and folks are looking to buy it. And Google also says that by this latest version they will try to create the operating system that can run everywhere and so android 4. 0 was urbanized. After thriving in android based device the necessity of android app developer is also thriving on quick way.

Below stated are some of the significant options of android 4. 0

1) Multi-tasking Button

Android 4. 0 comes with a virtual button that makes it simple to browse and quickly switch to apps you recently used. The list exhibits thumbnail images of apps–instead of just icons–so you can observe which part of the apps are at present functioning in the background. And, if you choose to throw away or discard an item on the list, simply just flick the thumbnail so that you can remove it from the list.

2) Face Unlock

Now neglect to remember password, pin codes, and patterns. Android 4. 0 ice cream sandwich has customized phone unlocking quite easy, with most recently released aspect on unlocking the device, now your android tablet can find the owner face and by that it will unlock.

3) Multiple keyboard languages

Consumers that converse multiple languages will really enjoy this characteristic. You can now add multiple languages to the keyboard and easily switch between Latin-based input languages by swiping across the space bar. Not only does this results the keys but it influences the auto-correct dictionary as well.

4) Instant Screenshots with Button Press

There are lots of occasions in which users wish to share others what is right now exhibited on your screen. There are also times when they just need to save a screenshot for later use. In previous versions of Android tutorials, they could take screenshots by installing apps for that purpose. In Android 4. 0, it’s a built-in feature. By sustaining the Power and Volume Down buttons together, your Android smartphone lets you grab screen images promptly.

5) Data Usage Monitoring

The Android 4 OS originates with an in-built ability to observe the data usage of the phone. Phones users normally fear of their data usage. Data prices are high once your go beyond the data usage limit. The new OS monitor the level of data utilized displays it in a nice graphical format to the user. Users can add extra warning signals for excess data usage limits. Further, data usage for each application can be set in advance for managed mobile data usage.

6) Powerful voice input engine

Android 4. 0 initiates a amazing new voice input engine that offers you a frequent “open microphone” experience and streaming voice recognition. Now you can speak continuously for a longed time, even pause for intervals if needed and dictate punctuation to create correct sentences. As the voice input engine enters text, it shows underlines to possible dictation errors in gray. You can tap the underlined words to rapidly replace them from a list of solutions.

7) Copy and Paste

Copy and paste overall performance got a re-vamp and is much easier to use. You can now move around whole blocks of text.

This upgrade only shows how committed Google is to making Android the top mobile operating system. As you can see, there are countless superb new options in Ice Cream Sandwich that make it a top contender in the mobile and tablet market. This also illustrates that we can expect many more great new things from Android development in the near future.

Posted in Android Tutorials | Tagged , , , , | Leave a comment

Android Development Tutorial-TableLayout

Android Development Tutorial-TableLayout
7.1. Overview

In earlier chapter we have used the LinearLayout which allows to stack widgets vertical or horizontal. LinearLayout can be nestled to archive nice effects. This chapter will demonstrate the usage of “TableLayout”.

This layout allows to organize view into a table format. You specify via the view group “TableRow” rows for your table. Afterwards you put widgets into the individual rows.

On the “TableLayout” you can define which column should take additional space via the “android:stretchColumns” attribute. If several columns should take the available space you can specific them as a comma-separated list. Similar you can use the attribute “android:shrinkColumn”, which will try to word-wrap the content of the specified widgets and the attribute “android:collapseColums” to define initially hidden columns. Via Java you can display / hide these columns via the method setColumnVisible().

Columns will be automatically created based on the maximum number of widgets in one row. Per default each widgets creates a new column in the row. You can specific via “android:layout_column” the column a widget should go and via “android:layout_span” how many columns a widget should take.

You can also put non TableRows in a table. This way you can for example add dividers between your columns.
7.2. Example

Create the project “de.vogella.android.layout.table” with the activity “DemoTableLayout”. Change “main.xml” to the following.

< ?xml version=”1.0″ encoding=”utf-8″?>

android:orientation=”vertical” android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
android:id=”@+id/tableLayout1″ android:layout_height=”wrap_content”
android:stretchColumns=”1″>
android:layout_height=”wrap_content” android:id=”@+id/tableRow1″>
android:layout_width=”wrap_content” android:layout_height=”wrap_content”>
android:layout_width=”wrap_content” android:layout_height=”wrap_content”
android:layout_column=”2″>
android:layout_height=”4px” android:background=”#FF0000″> 

android:layout_height=”wrap_content”>
android:layout_width=”wrap_content” android:id=”@+id/editText3″>
android:layout_width=”wrap_content” android:text=”Field4″
android:id=”@+id/editText4″>

Change the activity “DemoTableLayout” to the following to use the button to hide the second column in the table.
This Android Tutorial has been taken from Vogella click the link to read the entire android development tutorial.

Posted in Android Tutorials | Tagged , , , , , , , , , , | Leave a comment

Android Tutorial and Android Development Course for Beginners

Taught by real teachers who guide you
through every topic step by step.

Our Android Tutorial Training System Is Proven & Guaranteed

Our course creators and instructors have worked on mobile apps and mobile gaming projects published by top tier companies such as EA Mobile, iPlay, Oberon Media, Disney Mobile, Sony Pictures, Warner Bros, and Vodafone amongst others. They have been actively involved for over 7 years in the mobile industry through our associated sister company Chakra Interactive.

Inside The Android Training Program You Will …

Master Android Development via a fun and easy to learn system

Learn step-by-step via Online Video Android Tutorials, PDFs and Worksheets

Get direct guidance and live One-on-One Support from our Tutors

Take Weekly Exercises that are then reviewed and graded for you

Have Tutors chart and monitor your progress on a regular basis

Learn from the comfort of your home, at the time of your convenience

Work on a live commercial project as part of your final project

Get an EDUmobile certification for the full tenure of the course

Once candidates complete our Android course they may go on to independantly create and publish their own Android Apps, or work as Freelancers taking on Android projects for Clients from sites like Elance and oDesk, or they can directly benefit from a higher pay having enhanced their technical skill sets in a cutting edge technology space.

How We Conduct The Android Tutorials & Course

Our experienced team of developers and tutors have created and refined the course based on a proven system that works and is recognized in the industry.

The course will train you via a step-by-step, fun and easy to learn methodology where our Tutors are available to you via live chat and email throughout the course.

The tutors are available to help you whenever you face a road block, or anytime you are stuck with understanding a conceptual problem or you face coding issues or you just simply need their guidance.

You are never charged any extra fees whatsoever, for any tutor support throughout the entire duration of the 8 week course.

” We confidently say (and our students testify this) that, there is simply no other Android Training Program or Off-the-shelf Book that can match our methodology, our highly organized course material, the online training videos, the weekly worksheets, the access to live projects and the level of one-on-one support that is available throughout the term of the course.”

[1] Online Video Training – Once a Week. Delivered via broadband or DVD / CD via postal mail.

[2] One-on-One Interactive Online Support – Get 24 hour access by posting your issues and get help from our expert tutors quickly.

[3] Weekly PDFs and Worksheets – Read material and practice real problems and assignments as you go along.

[4] Live Industrial Project – One to two Live projects, with a choice to distribute the developed properties through various channels, and earn money.

[5] 24 x 7 Forum Access – Come to the members only online forum to meet other developers and discuss ideas and coding issues.

[6] EDUmobile Certification – Get a Certificate at the end of the course from EDUmobile – a recognized entity in the wireless industry.

[7] Access The Source Code Repository – Access and download over 100 valuable Source Code snippets that you can use freely in any of your projects for life.

[8] DVD & CD by mail* – At the end of the course, on request, we will send you all the content including bonus materials by postal mail.

LIMITED SEATS AVAILABLE – Sign Up at EDUmobile.ORG Android Development Course Today!

 

 


Posted in Android Tutorials | Tagged , , , , | Leave a comment

Android Tutorial-Making a custom Android button using a custom view

Android Tutorial-Making a custom Android button using a custom view

Creating a custom view is as simple as inheriting from the View class and overriding the methods that need to be overridden. In this example, a custom button is implemented in this way. The button shall feature a labelled image (i.e. an image with text underneath).

1 public class CustomImageButton extends View {
2 private final static int WIDTH_PADDING = 8;
3 private final static int HEIGHT_PADDING = 10;
4 private final String label;
5 private final int imageResId;
6 private final Bitmap image;
7 private final InternalListener listenerAdapter = new InternalListener();
8

The constructor can take in the parameters to set the button image and label.


9 /**
10 * Constructor.
11 *
12 * @param context
13 *        Activity context in which the button view is being placed for.
14 *
15 * @param resImage
16 *        Image to put on the button. This image should have been placed
17 *        in the drawable resources directory.
18 *
19 * @param label
20 *        The text label to display for the custom button.
21 */
22 public CustomImageButton(Context context, int resImage, String label)
23 {
24 super(context);
25 this.label = label;
26 this.imageResId = resImage;
27 this.image = BitmapFactory.decodeResource(context.getResources(),
28 imageResId);
29
30 setFocusable(true);
31 setBackgroundColor(Color.WHITE);
32
33 setOnClickListener(listenerAdapter);
34 setClickable(true);
35 }
36

With the constructor defined, there are a number of methods in the View class that needs to be overridden to this view behave like a button. Firstly, the onFocusChanged gets triggered when the focus moves onto or off the view. In the case of our custom button, we want the button to be “highlighted” when ever the focus is on the button.

This android tutorial to create and android button has been taken from the android development

tutorial by androidcore click the link to read the rest of the android tutorial

learn android programming

Posted in Android Tutorials | Tagged , , , , , , , , , | Leave a comment