Monday, October 22, 2012

Inside Android Manifest



The foundation for any Android application is the manifest file, AndroidManifest.xml in 
the root of your project. Here is where you declare what is inside your application—the activities, the services, and so on. You also indicate how these pieces attach themselves to the overall Android system; for example, you indicate which activity (or activities) should appear on the device’s main menu. 
When you create your application, a starter manifest will be generated for you
automatically. For a simple application, offering a single activity and nothing else, the autogenerated manifest will probably work out fine, or perhaps require a few minor modifications. On the other end of the spectrum, the manifest file for the Android API demo suite is more than 1,000 lines long. Your production  Android applications will probably fall somewhere in the middle.

Underneath the Manifest element


  • user permission elements: Indicate the permissions your application will need in order to function properly.
  • permission elements: Declare permissions that activities or services might require other applications to hold in order to use your application’s data or logic.
  • instrumentation elements: Indicate code that should be invoked on key system events, such as starting up activities, for the purposes of logging or monitoring.
  • uses-library elements: Hook in optional Android components, such as mapping services.
  • uses-sdk element: Indicates for which version of the Android SDK the application was built.
  • application element: Defines the guts of the application that the manifest describes.

Here’s an example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android">
<uses-permission
android:name="android.permission.ACCESS_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_GPS" />
<uses-permission
android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission
android:name="android.permission.ACCESS_CELL_ID" />
<application>
...
</application>
</manifest>
In this example, the manifest has uses permission elements to indicate some device capabilities the application will need—in this case, permissions to allow the application to determine its current location. The contents of the application element will describe the activities, services, and whatnot that make up the bulk of the application itself.

Inside Android Project



In this post I will share that what is inside the android project. When you open android project you will see many files and folder in it.

Src
In this folder you will see java files. Whatever you will work in java you will do in this folder.

Gen
This is generated java file and you will see R.java file in this folder. There is nothing to do with this file when you open this file you will see on the top it says that DO NOT MODIFY. Whenever you will add components or anything in android using XML then it will added in this folder ( source code will be generated In this file) and after adding component to this folder you can easily bind that component with java (through R.java file) and can do whatever you like to do with that component.

Assets
A folder that holds other static files you wish packaged with the application for deployment onto the device.

Res
In this resource folder you will see drawable-hdpi, drawable-ldpi, drawable-mdpi, layout and values folder. Let’s talk about layout first.  You will see main.xml file in layout and in this file you can make layout or you can say UI of android using XML. In Values folder there is string.xml file. This file help to make anything global ( means it can be use everywhere in application). If your project name is ABC and you want to use it anywhere in your project just add you project name ( p_name = ABC) now whenever you will call p_name you will see ABC and can easily change it(no need to change this name everywhere). Now let talk about drawable. If you want to add any picture in you project you will insert in this folder. But why three folder of drawable? High resolution pictures goes in hdpi, medium resolution in mdpi and low in ldpi.

Manifest.xml
An XML file describing the application being built and which components—activities, services, and so on—are being supplied by that application.

Default.properties and local.properties
Property files used by the Ant build script.

Res/drawable/:For images (PNG, JPEG, etc.).
Res/layout/:For XML-based UI layout specifications.
Res/menu/:For XML-based menu specifications.
Res/raw/:For general-purpose files (e.g., a CSV file of account
information).
Res/values/:For strings, dimensions, and the like.
Res/xml/:For other general-purpose XML files you wish to ship.

Android HorizontalScroll


Horizontal Scroll:-
Here is the implementation of Swipe and ScrollView working together: 

 HoriScroll.java

 package com.HoriScroll;

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

public class HoriScroll extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        FlingAndScrollViewer flingAndScrollViewer = (FlingAndScrollViewer) findViewById(R.id.flingScrollViewer);
        flingAndScrollViewer.setInitialPosition(0);
    }
}


FlingAndScrollViewer.java
package com.HoriScroll;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

public class FlingAndScrollViewer extends ViewGroup {
private Scroller mScroller;
private VelocityTracker mVelocityTracker;
 private int mScrollX = 0;
private int mCurrentScreen = 0;
 private float mLastMotionX;
 private static final String LOG_TAG = "FlingAndScrollViewer";
 private static final int SNAP_VELOCITY = 1000;
 private final static int TOUCH_STATE_REST = 0;
private final static int TOUCH_STATE_SCROLLING = 1;
 private int mTouchState = TOUCH_STATE_REST;
 private int mTouchSlop = 0;
 public FlingAndScrollViewer(Context context) {
    super(context);
    mScroller = new Scroller(context);
     mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
     this.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.FILL_PARENT));
}
 public FlingAndScrollViewer(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = getContext().obtainStyledAttributes(attrs,
            R.styleable.FlingAndScrollViewer);
    mCurrentScreen = a.getInteger(
            R.styleable.FlingAndScrollViewer_default_screen, 0);
     mScroller = new Scroller(context);
     mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
     this.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.FILL_PARENT));
 }
 public void setInitialPosition(int initialPosition){
    mCurrentScreen = initialPosition;
}
 @Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    /*
     * This method JUST determines whether we want to intercept the motion.
     * If we return true, onTouchEvent will be called and we do the actual
     * scrolling there.
     */
     /*
     * Shortcut the most recurring case: the user is in the dragging state
     * and he is moving his finger. We want to intercept this motion.
     */
    final int action = ev.getAction();
    if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
        return true;
    }
     final float x = ev.getX();
     switch (action) {
    case MotionEvent.ACTION_MOVE:
        /*
         * mIsBeingDragged == false, otherwise the shortcut would have
         * caught it. Check whether the user has moved far enough from his
         * original down touch.
         */
         /*
         * Locally do absolute value. mLastMotionX is set to the y value of
         * the down event.
         */
        final int xDiff = (int) Math.abs(x - mLastMotionX);
         boolean xMoved = xDiff > mTouchSlop;
         if (xMoved) {
            // Scroll if the user moved far enough along the X axis
            mTouchState = TOUCH_STATE_SCROLLING;
        }
        break;
     case MotionEvent.ACTION_DOWN:
        // Remember location of down touch
        mLastMotionX = x;
         /*
         * If being flinged and user touches the screen, initiate drag;
         * otherwise don't. mScroller.isFinished should be false when being
         * flinged.
         */
        mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST
                : TOUCH_STATE_SCROLLING;
        break;
     case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
        // Release the drag
        mTouchState = TOUCH_STATE_REST;
        break;
    }
     /*
     * The only time we want to intercept motion events is if we are in the
     * drag mode.
     */
    return mTouchState != TOUCH_STATE_REST;
}
 @Override
public boolean onTouchEvent(MotionEvent event) {
     if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(event);
     final int action = event.getAction();
    final float x = event.getX();
     switch (action) {
    case MotionEvent.ACTION_DOWN:
        Log.i(LOG_TAG, "event : down");
        /*
         * If being flinged and user touches, stop the fling. isFinished
         * will be false if being flinged.
         */
        if (!mScroller.isFinished()) {
            mScroller.abortAnimation();
        }
         // Remember where the motion event started
        mLastMotionX = x;
        break;
    case MotionEvent.ACTION_MOVE:
        // Log.i(LOG_TAG,"event : move");
        // if (mTouchState == TOUCH_STATE_SCROLLING) {
        // Scroll to follow the motion event
        final int deltaX = (int) (mLastMotionX - x);
        mLastMotionX = x;
         // Log.i(LOG_TAG, "event : move, deltaX " + deltaX + ", mScrollX " +
        // mScrollX);
         if (deltaX < 0) {
            if (mScrollX > 0) {
                scrollBy(Math.max(-mScrollX, deltaX), 0);
            }
        } else if (deltaX > 0) {
            final int availableToScroll = getChildAt(getChildCount() - 1)
                    .getRight() - mScrollX - getWidth();
            if (availableToScroll > 0) {
                scrollBy(Math.min(availableToScroll, deltaX), 0);
            }
        }
        // }
        break;
    case MotionEvent.ACTION_UP:
        Log.i(LOG_TAG, "event : up");
        // if (mTouchState == TOUCH_STATE_SCROLLING) {
        final VelocityTracker velocityTracker = mVelocityTracker;
        velocityTracker.computeCurrentVelocity(1000);
        int velocityX = (int) velocityTracker.getXVelocity();
         if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
            // Fling hard enough to move left
            snapToScreen(mCurrentScreen - 1);
        } else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
            // Fling hard enough to move right
            snapToScreen(mCurrentScreen + 1);
        } else {
            snapToDestination();
        }
         if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
        // }
        mTouchState = TOUCH_STATE_REST;
        break;
    case MotionEvent.ACTION_CANCEL:
        Log.i(LOG_TAG, "event : cancel");
        mTouchState = TOUCH_STATE_REST;
    }
    mScrollX = this.getScrollX();
     return true;
}
 private void snapToDestination() {
    final int screenWidth = getWidth();
    final int whichScreen = (mScrollX + (screenWidth / 2)) / screenWidth;
    Log.i(LOG_TAG, "from des");
    snapToScreen(whichScreen);
}
 public void snapToScreen(int whichScreen) {
    Log.i(LOG_TAG, "snap To Screen " + whichScreen);
    mCurrentScreen = whichScreen;
    final int newX = whichScreen * getWidth();
    final int delta = newX - mScrollX;
    mScroller.startScroll(mScrollX, 0, delta, 0, Math.abs(delta) * 2);
    invalidate();
}
 public void setToScreen(int whichScreen) {
    Log.i(LOG_TAG, "set To Screen " + whichScreen);
    mCurrentScreen = whichScreen;
    final int newX = whichScreen * getWidth();
    mScroller.startScroll(newX, 0, 0, 0, 10);
    invalidate();
}
 @Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int childLeft = 0;
     final int count = getChildCount();
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (child.getVisibility() != View.GONE) {
            final int childWidth = child.getMeasuredWidth();
            child.layout(childLeft, 0, childLeft + childWidth,
                    child.getMeasuredHeight());
            childLeft += childWidth;
        }
    }
 }
 @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
     final int width = MeasureSpec.getSize(widthMeasureSpec);
    final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    if (widthMode != MeasureSpec.EXACTLY) {
        throw new IllegalStateException("error mode.");
    }
     final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    if (heightMode != MeasureSpec.EXACTLY) {
        throw new IllegalStateException("error mode.");
    }
     // The children are given the same width and height as the workspace
    final int count = getChildCount();
    for (int i = 0; i < count; i++) {
        getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
    }
    Log.i(LOG_TAG, "moving to screen " + mCurrentScreen);
    scrollTo(mCurrentScreen * width, 0);
}
 @Override
public void computeScroll() {
    if (mScroller.computeScrollOffset()) {
        mScrollX = mScroller.getCurrX();
        scrollTo(mScrollX, 0);
        postInvalidate();
    }
}
 /**
 * Return the parceable instance to be saved
 */
@Override
protected Parcelable onSaveInstanceState() {
    final SavedState state = new SavedState(super.onSaveInstanceState());
    state.currentScreen = mCurrentScreen;
    return state;
}
 /**
 * Restore the previous saved current screen
 */
@Override
protected void onRestoreInstanceState(Parcelable state) {
    SavedState savedState = (SavedState) state;
    super.onRestoreInstanceState(savedState.getSuperState());
    if (savedState.currentScreen != -1) {
        mCurrentScreen = savedState.currentScreen;
    }
}
 // ========================= INNER CLASSES ==============================
 public interface onViewChangedEvent {
    void onViewChange(int currentViewIndex);
}
 /**
 * A SavedState which save and load the current screen
 */
public static class SavedState extends BaseSavedState {
    int currentScreen = -1;
     /**
     * Internal constructor
     *
     * @param superState
     */
    SavedState(Parcelable superState) {
        super(superState);
    }
     /**
     * Private constructor
     *
     * @param in
     */
    private SavedState(Parcel in) {
        super(in);
        currentScreen = in.readInt();
    }
     /**
     * Save the current screen
     */
    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeInt(currentScreen);
    }
     /**
     * Return a Parcelable creator
     */
    public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
        public SavedState createFromParcel(Parcel in) {
            return new SavedState(in);
        }
         public SavedState[] newArray(int size) {
            return new SavedState[size];
        }
    };
}
}


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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello"
        android:gravity="center" />
 <com.HoriScroll.FlingAndScrollViewer
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/flingScrollViewer">
        <ScrollView android:id="@+id/scrollView1"
            android:background="#FF8000" android:layout_height="fill_parent"
            android:layout_width="fill_parent">
            <LinearLayout android:id="@+id/linearLayout1"
                android:layout_height="fill_parent" android:layout_width="fill_parent"
                android:orientation="vertical">
                <TextView android:id="@+id/TextView01" android:text="1"
                    android:textColor="#ffffff" android:layout_width="fill_parent"
                    android:layout_weight="1" android:gravity="center"
                    android:layout_height="wrap_content" android:textSize="500dip"></TextView>
            </LinearLayout>
        </ScrollView>
     <ScrollView android:id="@+id/scrollView2"
            android:background="#0080FF" android:layout_height="fill_parent"
            android:layout_width="fill_parent">
            <LinearLayout android:id="@+id/linearLayout2"
                android:layout_height="fill_parent" android:layout_width="fill_parent"
                android:orientation="vertical">
                <TextView android:id="@+id/TextView02" android:text="2"
                    android:textColor="#ffffff" android:layout_width="fill_parent"
                    android:layout_weight="1" android:gravity="center"
                    android:layout_height="wrap_content" android:textSize="500dip"></TextView>
            </LinearLayout>
        </ScrollView>
     <ScrollView android:id="@+id/scrollView3"
            android:background="#00FF00" android:layout_height="fill_parent"
            android:layout_width="fill_parent">
            <LinearLayout android:id="@+id/linearLayout3"
                android:layout_height="fill_parent" android:layout_width="fill_parent"
                android:orientation="vertical">
                <TextView android:id="@+id/TextView03" android:text="3"
                    android:textColor="#ffffff" android:layout_width="fill_parent"
                    android:layout_weight="1" android:gravity="center"
                    android:layout_height="wrap_content" android:textSize="500dip"></TextView>
            </LinearLayout>
        </ScrollView>
 </com.HoriScroll.FlingAndScrollViewer>
</LinearLayout>

attrs.xml ( res/value)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="FlingAndScrollViewer">
        <attr name="default_screen" format="integer"/>
    </declare-styleable>
</resources>




Click Here to Download HoriScroll Project .

iPhone AlertView



AlertVIew in iphone with 2 buttons OK/YES/DELETE and NO/CANCEL .
// 2 Buttons
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wait" message:@"Are you sure you want to delete this.  This action cannot be undone" delegate:self cancelButtonTitle:@"Delete" otherButtonTitles:@"Cancel", nil];
[alert show];

Performing Action on Both Buttons i.e Delete and Cancel.
buttonIndex 0 for Delete
buttonIndex 1 for Cancel

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { 
   if (buttonIndex == 0) { 
        NSLog(@"Delete Tapped."); 
    } 
    else if (buttonIndex == 1) { 
       NSLog(@"Cancel Tapped!"); 
    } 
}

Same u can perform action with single button alert view.

AlertVIew in iphone with 1 buttons OK/YES
// 1 Button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wait" message:@"No INTERNET CONNECTION" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];

Saturday, May 14, 2011

Enumeration

Enumeration are declared using enum keyword. Enumeration are distinct type consisting of a set of names that are constant.
For example we know that days in week are constant so we can use enum for days and month also.
Each enum type has a corresponding integral type called the underlying type of the enum
type. This underlying type must be able to represent all the enumerator values defined in
the enumeration. An enum declaration may explicitly declare an underlying type of byte,
sbyte, short, ushort, int, uint, long, or ulong. Note that char cannot be used as an underlying
type. An enum declaration that does not explicitly declare an underlying type has an
underlying type of int.


Example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace test_practise
{
    public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
    class Program
    {
        static void Main(string[] args)
        {
            Days day = Days.Monday;
            Console.WriteLine((int)day);
            Console.WriteLine(day);
            Console.ReadLine();
        }
    }
}


You will see output 0. You can change the value of Monday from 0 to 1 by assigning value to Monday


public enum Days { Monday=1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

Tuesday, March 1, 2011

Interface

Interface is a comunicating media between two mediums. In c# multiple inheritance is not allowed that's why interface are used to fulfil the needs of multiple inheritance. As c# does not support multiple inheritance then it is necessary that the class can inherit the behaviour of more than one class, that's what interface provides us. In multiple inheritance we had a problem that if a class has two base class and both have some same methods then which method to call. Classes can inherit multiple interface.
Interface are contract of rules that a class which inherits it must follow(i.e must implement the method which are defined in interface). Interface contains method that do not contain any implementation just contain declaration of that method and the class which inherits it must implement those method. Interfaces can contain properties, indexers, and events but interface cannot contains field and interface cannot be instantiate.


Example



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace blog
{
    class Program
    {
        static void Main(string[] args)
        {
            circle objc = new circle();
            objc.fill();
            square objs = new square();
            objs.fill();
            line objl = new line();
            objl.draw();
            Console.ReadKey();
        }
    }
    interface fill
    {
        void fill();
    }
    class shapes  {
        public void draw()  {
            Console.WriteLine("shape Draw");
        }
    }
    class circle : shapes,fill    {
        public void fill()        {
            Console.WriteLine("Circle Fill");
        }
    }
    class square : shapes, fill    {
        public void fill()        {
            Console.WriteLine("Square Fill");
        }
    }
    class line : shapes    {
    }
}

Wednesday, February 16, 2011

Mathematical Table

Mathematical Table
Lets make a Program that take input and will show mathematical table.



static void Main(string[] args)
        {
            int table;            
            Console.WriteLine("Enter Table Number");
            table = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i < 13; i++)
            {
                Console.WriteLine(table + " x " + i + " = " + i * table); 
            }
            Console.ReadKey();   
        }


Lets make another program that will show mathematical table from 1 to 12.



static void Main(string[] args)
        {
            for (int i = 1; i < 11; i++)
                for (int j = 1; j < 13; j++)
                    Console.WriteLine(i + " x " + j + " = " + i * j);
            
            Console.ReadKey();   
        }