Saturday, April 30, 2011

Splash Screen In Android ....

.XML File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@drawable/splashbackground"
  android:layout_gravity="center"
  android:gravity="center"
  android:orientation="vertical">
 
  <ImageView
  android:src="@drawable/logo"
  android:layout_height="wrap_content"
  android:layout_width="wrap_content"
     android:id="@+id/logo"/>
    
     <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/shipbell"
     style="@style/textview"
android:layout_marginTop="8dip"
     />
</LinearLayout>


.JAVA File


package com.bell.shipclock;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

public class SplashScreen extends Activity {
    protected boolean _active = true;
    protected int _splashTime = 5000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.splashscreen);
       
        Thread splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    int waited = 0;
                    while(_active && (waited < _splashTime)) {
                        sleep(100);
                        if(_active) {
                            waited += 100;
                        }
                    }
                } catch(InterruptedException e) {
                    // do nothing
                } finally {
                    finish();
                    Intent intent =new Intent(SplashScreen.this, Home.class);
                    startActivity(intent);
                    stop();
                }
            }
        };
        splashTread.start();
       
       

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            _active = false;
        }
        return true;
    }
   
   

}

Splash Screen In Android ....

.XML File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@drawable/splashbackground"
  android:layout_gravity="center"
  android:gravity="center"
  android:orientation="vertical">
 
  <ImageView
  android:src="@drawable/logo"
  android:layout_height="wrap_content"
  android:layout_width="wrap_content"
     android:id="@+id/logo"/>
    
     <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/shipbell"
     style="@style/textview"
android:layout_marginTop="8dip"
     />
</LinearLayout>


.JAVA File


package com.bell.shipclock;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

public class SplashScreen extends Activity {
    protected boolean _active = true;
    protected int _splashTime = 5000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.splashscreen);
       
        Thread splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    int waited = 0;
                    while(_active && (waited < _splashTime)) {
                        sleep(100);
                        if(_active) {
                            waited += 100;
                        }
                    }
                } catch(InterruptedException e) {
                    // do nothing
                } finally {
                    finish();
                    Intent intent =new Intent(SplashScreen.this, Home.class);
                    startActivity(intent);
                    stop();
                }
            }
        };
        splashTread.start();
       
       

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            _active = false;
        }
        return true;
    }
   
   

}

Friday, April 29, 2011

spannable in android

.Java File

TextView forgot = (TextView) findViewById(R.id.text1);
        SpannableString content = new SpannableString("Forgot Password");
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        forgot.setText(content);
        forgot.setTextColor(Color.BLACK);

Android New Device (HoneyComb)


New User Features

New UI designed from the ground up for tablets

Android 3.0 is a new version of the Android platform that is specifically optimized for devices with larger screen sizes, particularly tablets. It introduces a brand new, truly virtual and “holographic” UI design, as well as an elegant, content-focused interaction model.
Android 3.0 builds on the things people love most about Android — refined multitasking, rich notifications, Home screen customization, widgets, and more — and transforms them with a vibrant, 3D experience and deeper interactivity, making them familiar but even better than before.
The new UI brings fresh paradigms for interaction, navigation, and customization and makes them available to all applications — even those built for earlier versions of the platform. Applications written for Android 3.0 are able to use an extended set of UI objects, powerful graphics, and media capabilities to engage users in new ways.





System Bar, for global status and notifications
Across the system and in all applications, users have quick access to notifications, system status, and soft navigation buttons in a System Bar, available at the bottom of the screen. The System Bar is always present and is a key touchpoint for users, but in a new "lights out mode" can also be dimmed for full-screen viewing, such as for videos.
Action Bar, for application control
In every application, users have access to contextual options, navigation, widgets, or other types of content in an Action Bar, displayed at the top of the screen. The Action Bar is always present when an application is in use, although its content, theme, and other properties are managed by the application rather than the system. The Action Bar is another key touchpoint for users, especially with action items and an overflow dropdown menu, which users frequently access in a similar manner in most applications.


Customizable Home screens
Five customizable Home screens give users instant access to all parts of the system from any context. Each screen offers a large grid that maintains spatial arrangement in all orientations. Users can select and manipulate Home screen widgets, app shortcuts, and wallpapers using a dedicated visual layout mode. Visual cues and drop shadows improve visibility when adjusting the layout of shortcuts and widgets. Each Home screen also offers a familiar launcher for access to all installed applications, as well as a Search box for universal search of apps, contacts, media files, web content, and more.




The Android 3.0 platform includes an updated set of standard applications that are designed for use on larger screen devices. The sections below highlight some of the new features.
Browser The browser includes new features that let users navigate and organize more efficiently. Multiple tabs replace browser windows and a new “incognito” mode allows anonymous browsing. Bookmarks and history are presented and managed in a single unified view. Users can now choose to automatically sign into Google sites on the browser with a supplied account and sync bookmarks with Google Chrome. New multitouch support is now available to JavaScript and plugins. Users can enjoy a better browsing experience at non-mobile sites through an improved zoom and viewport model, overflow scrolling, support for fixed positioning, and more.
Camera and Gallery
The Camera application has been redesigned to take advantage of a larger screen for quick access to exposure, focus, flash, zoom, front-facing camera, and more. To let users capture scenes in new ways, it adds built-in support for time-lapse video recording. The Gallery application lets users view albums and other collections in full-screen mode, with easy access to thumbnails for other photos in the collection.
Contacts
The Contacts app uses a new two-pane UI and Fast Scroll to let users easily organize and locate contacts. The application offers improved formatting of international phone numbers as user types, based on home country and an international number parsing library. Contact information is presented in a card-like UI, making it easier for users to read and edit contacts.
Email
The Email application uses a new two-pane UI to make viewing and organizing messages more efficient. The app lets users select one or more messages, then select an action from the Action Bar, such as moving them to a folder. Users can sync attachments for later viewing and keep track of email using a home screen Widget.


Wednesday, April 20, 2011

Auto change backgroundcolor by Seek bar in Android




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"
android:id="@+id/myScreen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<SeekBar
android:id="@+id/mySeekingBar_R"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
<SeekBar
android:id="@+id/mySeekingBar_G"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
<SeekBar
android:id="@+id/mySeekingBar_B"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
</LinearLayout>
 
SeekColorActivity.java 
 package com.exercise.seekcolor;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.SeekBar;

public class SeekColorActivity extends Activity {

private int seekR, seekG, seekB;
SeekBar redSeekBar, greenSeekBar, blueSeekBar;
LinearLayout mScreen;

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

    mScreen = (LinearLayout) findViewById(R.id.myScreen);
    redSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_R);
    greenSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_G);
    blueSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_B);
    updateBackground();

    redSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
    greenSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
    blueSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);

}

private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener()
{

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
  boolean fromUser) {
// TODO Auto-generated method stub
 updateBackground();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};

private void updateBackground()
{
 seekR = redSeekBar.getProgress();
 seekG = greenSeekBar.getProgress();
 seekB = blueSeekBar.getProgress();
 mScreen.setBackgroundColor(
  0xff000000
  + seekR * 0x10000
  + seekG * 0x100
  + seekB
  );
}
} 

Gridview Example in Android

.java File



package com.stress;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Mood extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mood);

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                Toast.makeText(Mood.this, "" + position, Toast.LENGTH_SHORT)
                        .show();

            }
        });
    }

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
        }

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

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

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

        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            View grid;

            if (convertView == null) { // if it's not recycled, initialize some
                // attributes
                grid = new View(mContext);
                LayoutInflater inflater = getLayoutInflater();
                grid = inflater.inflate(R.layout.moodcus, parent, false);

            } else {
                grid = (View) convertView;

            }
            ImageView imageView = (ImageView) grid.findViewById(R.id.imgview);
            TextView textView = (TextView) grid.findViewById(R.id.txtview);
            imageView.setImageResource(mThumbIds[position]);
            textView.setText(mMoodnames[position]);
            return grid;
        }

        // references to our images
        private Integer[] mThumbIds = { R.drawable.angry_text,
                R.drawable.bored, R.drawable.calm, R.drawable.confident,
                R.drawable.confused, R.drawable.cool, R.drawable.dipressed,
                R.drawable.elated, R.drawable.embrassed, R.drawable.evil,
                R.drawable.flirt, R.drawable.forgetfull, R.drawable.frusted,
                R.drawable.happy, R.drawable.hungry, R.drawable.impatient,
                R.drawable.inlove, R.drawable.insecure, R.drawable.irrited,
                R.drawable.jealous, R.drawable.lonely, R.drawable.nervous,
                R.drawable.pure, R.drawable.sad, R.drawable.satisfied,
                R.drawable.scared, R.drawable.shy, R.drawable.sick,
                R.drawable.stressed, R.drawable.tired };

        private String[] mMoodnames = { "Angry", "Bored", "Calm", "Confident",
                "Confused", "Cool", "Dipressed", "Elated", "Embrassed", "Evil",
                "Flirt", "Forgetfull", "Frusted", "Happy", "Hungry",
                "Impatient", "Inlove", "Insecure", "Irrited", "Jealous",
                "Lonely", "Nervous", "Pure", "Sad", "Satisfied", "Scared",
                "Shy", "Sick", "Stressed", "Tired" };
    }

}


mood.xml


<?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:background="@drawable/background">
    <RelativeLayout android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/grid">
        <GridView android:id="@+id/gridview" android:layout_width="fill_parent"
            android:scrollbars="none" android:layout_height="wrap_content"
            android:columnWidth="90dp" android:numColumns="4" android:fadingEdge="none"
            android:verticalSpacing="10dp" android:horizontalSpacing="10dp"
            android:stretchMode="columnWidth" android:gravity="center"
            android:layout_above="@+id/doneLay" android:layout_marginBottom="100dip" />
    </RelativeLayout>
    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/doneLay" android:layout_below="@+id/grid"
        android:layout_centerHorizontal="true" android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button android:layout_width="wrap_content" android:id="@+id/done"
            android:layout_weight="1" android:layout_marginTop="10dip"
            android:layout_centerHorizontal="true" android:layout_marginBottom="55dip"
            android:layout_marginLeft="15dip" android:background="@drawable/done"
            android:layout_height="wrap_content" android:text="@string/done"></Button>
    </RelativeLayout>

</RelativeLayout>



moodcus.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">
    <ImageView android:id="@+id/imgview" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_gravity="center" />
    <TextView android:id="@+id/txtview" android:layout_width="wrap_content"
        android:textColor="#6687B2" android:layout_height="wrap_content"
        android:layout_gravity="center" />
</LinearLayout>

How to us Tab Group Activity In Android

main.xml

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

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="#F4F4F4">

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

        <FrameLayout android:id="@android:id/tabcontent"
            android:layout_width="fill_parent" android:layout_height="wrap_content" />

        <TabWidget android:id="@android:id/tabs"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:gravity="bottom|center_horizontal"></TabWidget>

    </LinearLayout>
</TabHost>

TabGrouActivity.java

package com.statepermit;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;

/**
 * The purpose of this Activity is to manage the activities in a tab.
 * Note: Child Activities can handle Key Presses before they are seen here.
 * @author Eric Harlow
 */
public class TabGroupActivity extends ActivityGroup {

    private ArrayList<String> mIdList;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      
        if (mIdList == null) mIdList = new ArrayList<String>();
    }
 
    /**
     * This is called when a child activity of this one calls its finish method.
     * This implementation calls {@link LocalActivityManager#destroyActivity} on the child activity
     * and starts the previous activity.
     * If the last child activity just called finish(),this activity (the parent),
     * calls finish to finish the entire group.
     */
  @Override
  public void finishFromChild(Activity child) {
      LocalActivityManager manager = getLocalActivityManager();
      int index = mIdList.size()-1;
     
      if (index < 1) {
          finish();
          return;
      }
         
      manager.destroyActivity(mIdList.get(index), true);
      mIdList.remove(index); index--;
      String lastId = mIdList.get(index);
      Intent lastIntent = manager.getActivity(lastId).getIntent();
      Window newWindow = manager.startActivity(lastId, lastIntent);
      setContentView(newWindow.getDecorView());
  }
 
  /**
   * Starts an Activity as a child Activity to this.
   * @param Id Unique identifier of the activity to be started.
   * @param intent The Intent describing the activity to be started.
   * @throws android.content.ActivityNotFoundException.
   */
  public void startChildActivity(String Id, Intent intent) {    
      Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
      if (window != null) {
          mIdList.add(Id);
          Log.v("log_tag", "startchildactivity: " + mIdList.size() + ":" + Id);
          setContentView(window.getDecorView());
      }   
  }
 
  /**
   * The primary purpose is to prevent systems before android.os.Build.VERSION_CODES.ECLAIR
   * from calling their default KeyEvent.KEYCODE_BACK during onKeyDown.
   */
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
      Log.v("log_tag", "  this function involve when press-down " );
      if (keyCode == KeyEvent.KEYCODE_BACK) {
          //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
          onBackPressed();
          return true;
      }
      return super.onKeyDown(keyCode, event);
  }

  /**
   * Overrides the default implementation for KeyEvent.KEYCODE_BACK
   * so that all systems call onBackPressed().
   */
  @Override
  public boolean onKeyUp(int keyCode, KeyEvent event) {
     
      Log.v("log_tag", "  this function involve when press-up ");
      if (keyCode == KeyEvent.KEYCODE_BACK) {
          onBackPressed();
          return true;
      }
      return super.onKeyUp(keyCode, event);
  }
 
  /**
   * If a Child Activity handles KeyEvent.KEYCODE_BACK.
   * Simply override and add this method.
   */
  @Override
  public void  onBackPressed() {
      Log.v("log_tag", "this function involve when press back");
      int length = mIdList.size();
      Log.v("log_tag", "length: " + length);
      if (length >= 1) {
          Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1));
          Log.v("log_tag", "the child view :"+current);
          this.finishFromChild(current);
      }
 
  }
}


StatePermitApplication.java

package com.statepermit;

import android.app.Application;

public class StatePermitApplication extends Application {

    private static String from = "state";

    public static String getFrom() {
        return from;
    }

    public static void setFrom(String fromPage) {
        from = fromPage;
    }
}




statepermit.java

package com.statepermit;

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;

public class statepermit extends TabActivity
{
    TabHost mTabHost;
    TabWidget mTabWidget;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Resources res = getResources();
        mTabHost = getTabHost();
        TabHost.TabSpec spec;
        mTabWidget = mTabHost.getTabWidget();
        Intent intent;

        intent = new Intent().setClass(this, Home.class);
        spec = mTabHost.newTabSpec(getString(R.string.state))
                .setIndicator("Home", res.getDrawable(R.drawable.home))
                .setContent(intent);
        mTabHost.addTab(spec);

        intent = new Intent().setClass(this, Search.class);
        spec = mTabHost.newTabSpec("Search")
                .setIndicator("Search", res.getDrawable(R.drawable.search))
                .setContent(intent);
        mTabHost.addTab(spec);

        intent = new Intent().setClass(this, Back.class);
        spec = mTabHost.newTabSpec("Back")
                .setIndicator("Back", res.getDrawable(R.drawable.back))
                .setContent(intent);
        mTabHost.addTab(spec);

        for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++)
        {
            mTabHost.getTabWidget().getChildAt(i)
                    .setBackgroundColor(Color.parseColor("#CCCCCC"));
            TextView tv = (TextView) mTabWidget.getChildAt(i).findViewById(
                    android.R.id.title);
            tv.setTextColor(Color.BLACK);
        }

        mTabHost.getTabWidget().getChildAt(0)
                .setBackgroundColor(Color.parseColor("#FFFFFF"));

        mTabHost.setCurrentTab(0);
       
        mTabHost.setOnTabChangedListener(new OnTabChangeListener()
        {
            @Override
            public void onTabChanged(String tabId)
            {
                int tab = mTabHost.getCurrentTab();
                if (tab == 0)
                {
                    mTabHost.getTabWidget().getChildAt(1)
                            .setBackgroundColor(Color.parseColor("#CCCCCC"));
                    mTabHost.getTabWidget().getChildAt(2)
                            .setBackgroundColor(Color.parseColor("#CCCCCC"));
                }
                else if (tab == 1)
                {
                    mTabHost.getTabWidget().getChildAt(0)
                            .setBackgroundColor(Color.parseColor("#CCCCCC"));
                    mTabHost.getTabWidget().getChildAt(2)
                            .setBackgroundColor(Color.parseColor("#CCCCCC"));
                }
                else
                {
                    mTabHost.getTabWidget().getChildAt(0)
                            .setBackgroundColor(Color.parseColor("#CCCCCC"));
                    mTabHost.getTabWidget().getChildAt(1)
                            .setBackgroundColor(Color.parseColor("#CCCCCC"));
                }

                mTabHost.getTabWidget().getChildAt(tab)
                        .setBackgroundColor(Color.WHITE);
            }
        });
    }
}



Login.java


package com.statepermit;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Login extends TabGroupActivity {

    protected static final String TAG = Login.class.getName();
    private static final String LOG = "log_tag";
    public static XMLParser xmlParser;
    public static User myUser;
    private EditText urname;
    private EditText urpass;
    private String username;
    private String password;
    public String myError;
    private Dialog dialog;
    int l = 0;
    protected ProgressDialog mProgressDialog;

    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.v(LOG, "Message Received");
            if (msg.what == 0) {
                Log.v("log_tag", "Print Error Message");
                errorMessage();
            }
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        Log.v("log_tag", "from where" + StatePermitApplication.getFrom());

        TextView forgot = (TextView) findViewById(R.id.text1);
        SpannableString content = new SpannableString("Forgot Password");
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        forgot.setText(content);
        forgot.setTextColor(Color.BLACK);

        forgot.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(Login.this, Forgotpassword.class);
                StatePermitApplication.setFrom("state_login");
                startChildActivity("forgot", intent);

            }
        });

        StatePermitApplication.setFrom("state");
        Button login = (Button) findViewById(R.id.button1);

        urname = (EditText) findViewById(R.id.edit1);
        urpass = (EditText) findViewById(R.id.edit2);
       
        login.setOnClickListener(new OnClickListener() {
    @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                username = urname.getText().toString().trim();
                password = urpass.getText().toString().trim();

                if (username.equals("") && password.equals("")) {
                    Log.v("log_tag", "data is blank");
                    insertdata();
                } else {

                    if (checkInternetConnection()) {
                       
                        //Login.this.showDialog(1);
                        mProgressDialog=ProgressDialog.show(getParent(), "Please Wait", "Login In Process", true);

                        new LoadUserData()
                                .execute(
                                        "http://www.retailpermits.com/WebServices/iPhone/WS_iPhone.asmx/ValidateUser?strUserName="
                                                + username
                                                + "&strPassword="
                                                + password, username, password);
                        StateApplicationClass.setLoginname(username);
                        StateApplicationClass.setPassword(password);
                       
                        Log.v("log_tag",
                                "Full Path :"
                                        + "http://www.retailpermits.com/WebServices/iPhone/WS_iPhone.asmx/ValidateUser?strUserName="
                                        + username + "&strPassword=" + password);
                    } else {
                        // showInternetErrorDialog();
                        internetError();
                        Log.e(TAG, "Internet Error: ");
                    }
                }
            }

        });
    }

    private class LoadUserData extends AsyncTask<String, Integer, Integer> {
        protected Integer doInBackground(String... paths) {
            String url;
            int type;
            try {
                url = paths[0];
                Log.v("log_tag", "URL: " + url);
                xmlParser = new XMLParser("ValidateUser");
                xmlParser.parseUser(url);

                if (xmlParser.getUserId() < 0) {
                    myError = "Could not complete the login. Try again later.";
                    type = 0;
                    Log.v("log_tag", "Error: " + myError);
                } else {
                    type = 1;
                    Log.v("log_tag", "XMLPARSER: " + xmlParser.getUserId());
                }
                return type;
            } catch (Exception e) {
                Log.v("log_tag", "Exception: " + e.toString());
            }
            return 0;
        }

        protected void onPostExecute(Integer result) {
            //dialog.dismiss();
            mProgressDialog.dismiss();
            if (result == 1) {
                Log.v("log_tag", "Succesfully Login");
                Intent intent = new Intent(Login.this, Info.class);
                StatePermitApplication.setFrom("state_login");
                startChildActivity("state_info", intent);
                // startActivity(intent);
                l = xmlParser.getUserId();
            } else if (result == 0) {
                // errorMessage();
                // showErrorMessage(myError);
                Log.v("log_tag", "the wrong password");
                Message msg = new Message();
                msg.what = 0;
                myHandler.sendMessage(msg);
                Log.v("log_tag", "Message Sent");
            }
        }
    }

    private boolean checkInternetConnection() {

        ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        // ARE WE CONNECTED TO THE NET
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) {

            return true;

        } else {
            Log.v(TAG, "Internet Connection Not Present");
            return false;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.DONUT
                && keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            onBackPressed();
        }

        return super.onKeyDown(keyCode, event);
    }

    public void onBackPressed() {
        Log.v("log_tag", "On home Back");
        Intent intent = new Intent(Login.this, statepermit.class);
        StatePermitApplication.setFrom("state");
        startActivity(intent);
        finish();
        return;
    }

    private void internetError() {

        AlertDialog.Builder alt_bld = new AlertDialog.Builder(getParent());
        alt_bld.setMessage(R.string.con_error_text)
                .setCancelable(false)
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // Action for 'Yes' Button

                            }
                        })
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // Action for 'NO' Button
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = alt_bld.create();
        // Title for AlertDialog
        alert.setTitle(R.string.connection_error);
        // Icon for AlertDialog
        // alert.setIcon(R.drawable.icon);
        alert.show();

    }

    private void errorMessage() {
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(getParent());
        alt_bld.setMessage(R.string.error_message)
                .setCancelable(false)
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // Action for 'Yes' Button
                            }
                        });
        AlertDialog alert = alt_bld.create();
        // Title for AlertDialog
        alert.setTitle(R.string.error);
        alert.show();

    }
    private void insertdata() {

        AlertDialog.Builder alt_bld = new AlertDialog.Builder(getParent());
        alt_bld.setMessage(R.string.insertdata)
                .setCancelable(false)
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // Action for 'Yes' Button
                            }
                        });
        AlertDialog alert = alt_bld.create();
        // Title for AlertDialog
        alert.setTitle(R.string.error);
        alert.show();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == 1) {
            if (dialog == null) {
                dialog = new Dialog(getParent());
                dialog.setTitle(R.string.please_wait);

            }
            return dialog;
        }
        return super.onCreateDialog(id);
    }

}

Tuesday, April 19, 2011

AMAZON Product

 

Monday, April 18, 2011

XMl Parsing With SAX Parser


example.xml

[sourcecode language="xml"]
<maintag>
<item>
<name>AndroidPeople</name>
<website category="android">www.androidpeople.com</website>
</item>
<item>
<name>iPhoneAppDeveloper</name>
<website category="iPhone">www.iphone-app-developer.com</website>
</item>
</maintag>
[/sourcecode]

 XMLParsingExample.java
 

package com.androidpeople.xml.parsing;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getName().size()];
category = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Website = "+sitesList.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+sitesList.getCategory().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}
[/sourcecode]

MyXMLHandler.java


package com.androidpeople.xml.parsing;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("maintag"))
{
/** Start */
sitesList = new SitesList();
} else if (localName.equals("website")) {
/** Get attribute value */
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}
}
/** Called when tag closing ( ex:- <name>AndroidPeople</name>
* -- </name> )*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("name"))
sitesList.setName(currentValue);
else if (localName.equalsIgnoreCase("website"))
sitesList.setWebsite(currentValue);
}
/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
* -- to get AndroidPeople Character ) */
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
[/sourcecode]

SitesList.java


package com.androidpeople.xml.parsing;
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> website = new ArrayList<String>();
private ArrayList<String> category = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
public ArrayList<String> getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website.add(website);
}
public ArrayList<String> getCategory() {
return category;
}
public void setCategory(String category) {
this.category.add(category);
}
}
[/sourcecode] 

Android Screen Orientation

Change /your Acreen Orientation to your Code in  Androidmanifest.xml,
if you want partrait and Landscape then select both

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.statepermit" android:versionCode="1" android:versionName="1.0">
    <application android:icon="@drawable/stateheader" android:label="@string/app_name">
        <activity android:name=".statepermit" android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar" android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
    </application>
    <uses-sdk android:minSdkVersion="7" />

</manifest>

Sunday, April 17, 2011

how to change Image In Android

Put this code in ur Program 
 
 .XML file
<Button android:id="@+id/btnLogin" android:text="Login"
        android:background="@drawable/my_button" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textColor="#FFFFFF"
        android:layout_marginTop="20dip"
        />

/drawable/button_login.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/loginblue" />
    <item android:drawable="@drawable/login_bt" />
    <item android:state_focused="true" android:drawable="@drawable/loginblue" />
</selector>

Android NotePad Tutorial

Notepad Tutorial

This tutorial on writing a notepad application gives you a "hands-on" introduction to the Android framework and the tools you use to build applications on it. Starting from a preconfigured project file, it guides you through the process of developing a simple notepad application and provides concrete examples of how to set up the project, develop the application logic and user interface, and then compile and run the application.
The tutorial presents the application development as a set of exercises (see below), each consisting of several steps. You should follow the steps in each exercise to gradually build and refine your application. The exercises explain each step in detail and provide all the sample code you need to complete the application.
When you are finished with the tutorial, you will have created a functioning Android application and will have learned many of the most important concepts in Android development. If you want to add more complex features to your application, you can examine the code in an alternative implementation of a Note Pad application, in the Sample Code section.

Who Should Use this Tutorial

This tutorial is designed for experienced developers, especially those with knowledge of the Java programming language. If you haven't written Java applications before, you can still use the tutorial, but you might need to work at a slower pace.
Also note that this tutorial uses the Eclipse development environment, with the Android plugin installed. If you are not using Eclipse, you can follow the exercises and build the application, but you will need to determine how to accomplish the Eclipse-specific steps in your environment.

Preparing for the Exercises

The tutorial assumes that you have some familiarity with basic Android application concepts and terminology. If you are not, you should read Application Fundamentals before continuing.
This tutorial also builds on the introductory information provided in the Hello World tutorial, which explains how to set up your Eclipse environment for building Android applications. We recommend you complete the Hello World tutorial before starting this one.
To prepare for this lesson:
  1. Download the project exercises archive (.zip).
  2. Unpack the archive file to a suitable location on your machine.
  3. Open the NotepadCodeLab folder.
Inside the NotepadCodeLab folder, you should see six project files: Notepadv1, Notepadv2, Notepadv3, Notepadv1Solution, Notepadv2Solution and Notepadv3Solution. The Notepadv# projects are the starting points for each of the exercises, while the Notepadv#Solution projects are the exercise solutions. If you are having trouble with a particular exercise, you can compare your current work against the exercise solution.

Exercises

The table below lists the tutorial exercises and describes the development areas that each covers. Each exercise assumes that you have completed any previous exercises.
Exercise 1 Start here. Construct a simple notes list that lets the user add new notes but not edit them. Demonstrates the basics of ListActivity and creating and handling menu options. Uses a SQLite database to store the notes.
Exercise 2 Add a second Activity to the application. Demonstrates constructing a new Activity, adding it to the Android manifest, passing data between the activities, and using more advanced screen layout. Also shows how to invoke another Activity to return a result, using startActivityForResult().
Exercise 3 Add handling of life-cycle events to the application, to let it maintain application state across the life cycle.
Extra Credit Demonstrates how to use the Eclipse debugger and how you can use it to view life-cycle events as they are generated. This section is optional but highly recommended.

Other Resources and Further Learning

  • For a lighter but broader introduction to concepts not covered in the tutorial, take a look at Common Android Tasks.
  • The Android SDK includes a variety of fully functioning sample applications that make excellent opportunities for further learning. You can find the sample applications in the samples/ directory of your downloaded SDK, or browser them here, in the Sample Code section.
  • This tutorial draws from the full Notepad application included in the samples/ directory of the SDK, though it does not match it exactly. When you are done with the tutorial, it is highly recommended that you take a closer look at this version of the Notepad application, as it demonstrates a variety of interesting additions for your application, such as:
    • Setting up a custom striped list for the list of notes.
    • Creating a custom text edit view that overrides the draw() method to make it look like a lined notepad.
    • Implementing a full ContentProvider for notes.
    • Reverting and discarding edits instead of just automatically saving them.

Android Layout

Hello, Views

This is a collection of "Hello World"-style tutorials designed to get you started quickly with common Android layouts and widgets.
A certain amount of knowledge is assumed for these tutorials. Before you start, you should have completed the Hello, World tutorial—it will teach you several things about basic Android development. More specifically, you should know:
  • How to create an Android project and run it
  • The basic structure of an Android project (resource files, layout files, etc.)
  • The basic components of an Activity
Note: In order to make these tutorials as simple as possible, some code may not conform to best practices for coding Android applications. In particular, hard-coded strings are used in places, when the better practice is to reference strings from a res/values/strings.xml resource file.
Tip: After you have pasted sample code into an Eclipse project, press Ctrl (or Cmd) + Shift + O to import the required packages.

Layouts


Widgets & Other Views

There are plenty more layouts and widgets available. See the View class for more on View layouts, and the widget package for more useful widgets. And for more raw code samples, visit the Api Demos.