Friday, March 30, 2012

Android 9 Patch Image Tutorial

This tutorial describes what Android 9 patch images are, how to make them, and how to use 9 Patch images in Android applications.

What is a 9 Patch Image?



A 9 patch image is an image that has stretchable areas defined.
These areas are defined in a special 1 pixel wide border around the area. Add black pixels to the top and left of this border to describe where the image can be stretched horizontally and vertically.


Why Use 9 Patch Images?



Nine patch images are especially useful when designing buttons. Custom drawn buttons can look distorted and pixelated when their borders are stretched in addition to the rest of the image.

Creating 9 Patch Images



Making a 9 Patch image is a fairly easy process. Included as part of the Android SDK is a Draw 9 Patch utility. Navigate to the folder where you installed the SDK. From there navigate to the tools folder. Inside this folder will be the draw 9 patch program. On Windows, double click on draw9patch.bat




Once the Draw 9 Patch program has started, simply drag an image that you would like to edit onto the program.


After an image has been loaded into the Draw 9-Patch program two panes of information will appear. The left pane is used to edit the patches. The right pane shows what the image will look like when it is stretched in a couple of different ways.





Drawing the Patches

You can think of the Draw 9 Patch program as a simple image editor, but you can only change the 1 pixel border and you can only use the color black.

Draw along the top of the image to define the area that can be stretched horizontally. Draw along the left side of the image to define the area that can be stretched vertically. Draw along the bottom and the right of the image to define the padding. Holding down shift and clicking will erase pixels.





If you have the "Show Patches" option selected, then the stretchable area will be highlighted in pink.
.9.png File Extension

Your nine patch images must be saved with the .9.png file extension in order for Android to recognize and handle them properly. Failure to do so may result in unpredictable results.

When you save from the Draw 9-Patch program it will have the proper extension.






Optional controls include:

Zoom: Adjust the zoom level of the graphic in the drawing area.
Patch scale: Adjust the scale of the images in the preview area.
Show lock: Visualize the non-drawable area of the graphic on mouse-over.
Show patches: Preview the stretchable patches in the drawing area (pink is a stretchable patch).
Show content: Highlight the content area in the preview images (purple is the area in which content is allowed).
Show bad patches: Adds a red border around patch areas that may produce artifacts in the graphic when stretched. Visual coherence of your stretched image will be maintained if you eliminate all bad patches.



Here are some examples

 Simple button

This is a just simple button, with a glowing effect. The 9patching wich I use here, keeps the button’s edges, so it keeps the rounded rectangle’s radius too. With 9patch, the content area of the button can be set easily.



Spinner button

This is a chooser button, with the same glowing effect. With this 9patching, the dropdown arrow keeps it’s size at horizontal stretching. The glowing effect stays in the middle of the button.





Article header image

In this case, I use an extra transparent line before and below the image. The 9patch stretches this lines out. The picture always align to the right top corner of the layout. This can be a spectacular articleheader background. 



Header background

Like at web pages, larger background images can created easily from a tiny picture. This 9patch stretches the middle of the image, so it’s look like continuous. The lenght of the layout doesn’t matter. For example, this is useful when creating menu bars.

Header background 2

In this example, I use the last column of the image, for horizontal stretch. This must be a single-color column. The image starts at the left side of the layout, in any cases, and fill the end with the single-color.


Search EditText

You can create your own, horizontal stretch - independent EditText with 9patching. Take care of setting the content area of the image, see it below.



Custom radio button and checkbox in android

Anybody know that real cool Android application must have not only excelent business logic. The one of the most important things what application must have is a nice UI.
If you want to create realy interesting application you need to create good UI. And …. hire a designer
Below i want to tell you how to create your own CheckBoxes and RadioButtons for your Android Applications. Sorry for this sample UI design. I didn’t hire a designer :).
First look at video of that:


<?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="wrap_content"
  android:textAppearance="?android:attr/textAppearanceLarge" 
  android:id="@+id/textView1"
  android:layout_height="wrap_content" 
  android:text="Custom Radio Button "/>
 <RadioGroup 
  android:id="@+id/radioGroup1"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content">
  <RadioButton 
   android:text="Cool" 
   android:button="@drawable/my_ratingbar"
   android:layout_height="wrap_content" 
   android:id="@+id/radio0"
   android:layout_width="134dp"/>
  <RadioButton 
   android:text="Sexy" 
   android:button="@drawable/my_ratingbar"
   android:layout_height="wrap_content" 
   android:id="@+id/radio1"
   android:checked="true" 
   android:layout_width="wrap_content"/>
  <RadioButton 
   android:text="Both" 
   android:button="@drawable/my_ratingbar"
   android:layout_height="wrap_content" 
   android:id="@+id/radio2"
   android:layout_width="wrap_content"/>
 </RadioGroup>
 <TextView 
  android:layout_width="wrap_content"
  android:textAppearance="?android:attr/textAppearanceLarge"
  android:layout_marginTop="20dp" 
  android:id="@+id/textView1"
  android:layout_height="wrap_content" 
  android:text="Custom Check Box "/>
 <CheckBox 
  android:text="CheckBox1" 
  android:id="@+id/checkBox1"
  android:checked="true" 
  android:button="@drawable/my_ratingbar"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content"/>
 <CheckBox 
  android:text="CheckBox2" 
  android:id="@+id/checkBox2"
  android:button="@drawable/my_ratingbar" 
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>
 <TextView 
  android:layout_width="wrap_content"
  android:textAppearance="?android:attr/textAppearanceLarge"
  android:layout_marginTop="20dp" 
  android:id="@+id/textView1"
  android:layout_height="wrap_content" 
  android:text="http://developer-dot-android.blogspot.com"/>
</LinearLayout>




my_ratingbar.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_checked="true" android:drawable="@drawable/red_holo" />
 <item android:state_checked="false" android:drawable="@drawable/red_full" />
</selector>

red_holo


red_full


Monday, March 26, 2012

Marquee effect in TextView tutorial

Here is the code

xml File

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/mywidget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:lines="1"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:textColor="#ff4500"
        android:text="Simple application that shows how to use marquee, with a long text" />
</RelativeLayout>

java file

public class TextViewMarquee extends Activity {
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) this.findViewById(R.id.tv);  
        tv.setSelected(true);  // Set focus to the textview
    }
}

Thursday, March 22, 2012

Sending Emails without User Interaction in Android


In this article I'm going to show you how to send an email in the background without the user even knowing - the application will do everything behind the scenes.
Before we begin, you'll need to download a few files via the link below - this is a special version of the JavaMail API, which was written specifically for Android.

I'll be walking you through a Mail wrapper that I wrote, which makes it much easier to send emails and even add attachments if that's something you'd like to do.
Here is the full wrapper class below, which I'll go through step by step - keeping in mind that you'll have to add the fore-said files if you want this to work. Add them as external libraries - they need to be accessible by the Mail class.


import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail extends javax.mail.Authenticator {
 private String _username;
 private String _password;

 private String[] _to;
 private String _from;

 private String _port;
 private String _sport;

 private String _host;

 private String _subject;
 private String _body;

 private boolean _auth;

 private boolean _debuggable;

 private Multipart _multipart;

 public Mail() {
  _host = "smtp.gmail.com"; // default smtp server
  _port = "465"; // default smtp port
  _sport = "465"; // default socketfactory port

  _username = ""; // username
  _password = ""; // password
  _from = ""; // email sent from
  _subject = ""; // email subject
  _body = ""; // email body

  _debuggable = false; // debug mode on or off - default off
  _auth = true; // smtp authentication - default on

  _multipart = new MimeMultipart();

  // There is something wrong with MailCap, javamail can not find a
  // handler for the multipart/mixed part, so this bit needs to be added.
  MailcapCommandMap mc = (MailcapCommandMap) CommandMap
    .getDefaultCommandMap();
  mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
  mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
  mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
  mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
  mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
  CommandMap.setDefaultCommandMap(mc);
 }

 public Mail(String user, String pass) {
  this();

  _username = user;
  _password = pass;

 }

 public boolean send() throws Exception {
  Properties props = _setProperties();

  if (!_username.equals("") && !_password.equals("") && _to.length > 0
    && !_from.equals("") && !_subject.equals("")
    && !_body.equals("")) {
   Session session = Session.getInstance(props, this);

   MimeMessage msg = new MimeMessage(session);

   msg.setFrom(new InternetAddress(_from));

   InternetAddress[] addressTo = new InternetAddress[_to.length];
   for (int i = 0; i < _to.length; i++) {
    addressTo[i] = new InternetAddress(_to[i]);
   }
   msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

   msg.setSubject(_subject);
   msg.setSentDate(new Date());

   // setup message body
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setText(_body);
   _multipart.addBodyPart(messageBodyPart);

   // Put parts in message
   msg.setContent(_multipart);

   // send email
   Transport.send(msg);

   return true;
  } else {
   return false;
  }
 }

 public void addAttachment(String filename) throws Exception {
  BodyPart messageBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(filename);
  messageBodyPart.setDataHandler(new DataHandler(source));
  messageBodyPart.setFileName(filename);

  _multipart.addBodyPart(messageBodyPart);
 }

 @Override
 public PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication(_username, _password);
 }

 private Properties _setProperties() {
  Properties props = new Properties();

  props.put("mail.smtp.host", _host);

  if (_debuggable) {
   props.put("mail.debug", "true");
  }

  if (_auth) {
   props.put("mail.smtp.auth", "true");
  }

  props.put("mail.smtp.port", _port);
  props.put("mail.smtp.socketFactory.port", _sport);
  props.put("mail.smtp.socketFactory.class",
    "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.socketFactory.fallback", "false");

  return props;
 }

 // the getters and setters
 public String getBody() {
  return _body;
 }

 public void setBody(String _body) {
  this._body = _body;
 }

 public void sendTo(String[] _to) {
  this._to = _to;
 }

 public void sendFrom(String _from) {
  this._from = _from;
 }
 public void setSubject(String _subject) {
  this._subject = _subject;
 }

 

 // more of the getters and setters …..
}

And now I'm going to go through each bit of code

public Mail() {
  _host = "smtp.gmail.com"; // default smtp server
  _port = "465"; // default smtp port
  _sport = "465"; // default socketfactory port

  _username = ""; // username
  _password = ""; // password
  _from = ""; // email sent from
  _subject = ""; // email subject
  _body = ""; // email body

  _debuggable = false; // debug mode on or off - default off
  _auth = true; // smtp authentication - default on

  _multipart = new MimeMultipart();

  // There is something wrong with MailCap, javamail can not find a
  // handler for the multipart/mixed part, so this bit needs to be added.
  MailcapCommandMap mc = (MailcapCommandMap) CommandMap
    .getDefaultCommandMap();
  mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
  mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
  mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
  mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
  mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
  CommandMap.setDefaultCommandMap(mc);
 }

 public Mail(String user, String pass) {
  this();

  _username = user;
  _password = pass;

 }

In this piece of code we initialise the properties, and setup the default values.
Also, we're setting up the mime types for javamail. I've also added a comment which describes why we need this.
And you've probably noticed that there are 2 constructors - one overrides the other, just incase the you want to pass the username and password when instantiating the class.

public boolean send() throws Exception {
  Properties props = _setProperties();

  if (!_username.equals("") && !_password.equals("") && _to.length > 0
    && !_from.equals("") && !_subject.equals("")
    && !_body.equals("")) {
   Session session = Session.getInstance(props, this);

   MimeMessage msg = new MimeMessage(session);

   msg.setFrom(new InternetAddress(_from));

   InternetAddress[] addressTo = new InternetAddress[_to.length];
   for (int i = 0; i < _to.length; i++) {
    addressTo[i] = new InternetAddress(_to[i]);
   }
   msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

   msg.setSubject(_subject);
   msg.setSentDate(new Date());

   // setup message body
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setText(_body);
   _multipart.addBodyPart(messageBodyPart);

   // Put parts in message
   msg.setContent(_multipart);

   // send email
   Transport.send(msg);

   return true;
  } else {
   return false;
  }
 }

This is the most important method - here we're putting all the data from the properties and sending the mail.
public void addAttachment(String filename) throws Exception {
  BodyPart messageBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(filename);
  messageBodyPart.setDataHandler(new DataHandler(source));
  messageBodyPart.setFileName(filename);

  _multipart.addBodyPart(messageBodyPart);
 }

You can call this method at any time if you want to add an attachment, but make sure you call it before the send method.
private Properties _setProperties() {
  Properties props = new Properties();

  props.put("mail.smtp.host", _host);

  if (_debuggable) {
   props.put("mail.debug", "true");
  }

  if (_auth) {
   props.put("mail.smtp.auth", "true");
  }

  props.put("mail.smtp.port", _port);
  props.put("mail.smtp.socketFactory.port", _sport);
  props.put("mail.smtp.socketFactory.class",
    "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.socketFactory.fallback", "false");

  return props;
 }


Here we're setting up the properties for the mail retrieval - defaulting to SMTP authentication. Also keep in mind that this is all defaulted to connect to the Gmail (Google) SMTP server. Below is an example of how to use the Mail wrapper, in an Android activity.
@Override
      public void onClick(View v) {
       // TODO Auto-generated method stub
       if (mEmail.getText().toString().equals(
         appPrefs.getEmail())) {
        Mail m = new Mail("email@gmail.com", "password"); 
         
             String[] toArr = {mEmail.getText().toString()}; 
             m.sendTo(toArr); 
             m.sendFrom("email@gmail.com"); 
             m.setSubject("Password"); 
             m.setBody("This is your password : " + appPrefs.getPassword()); 
        
             try { 
               m.addAttachment("/sdcard/filelocation"); 
        
               if(m.send()) { 
                 Toast.makeText(password.this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
               } else { 
                 Toast.makeText(password.this, "Email was not sent.", Toast.LENGTH_LONG).show(); 
               } 
             } catch(Exception e) { 
               //Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show(); 
               Log.e("Password", "Could not send email", e); 
             } 
        
       } else {
        
        Toast
          .makeText(
            getBaseContext(),
            "This is not that email which you enter when create account",
            Toast.LENGTH_LONG).show();
       }
      }
     });

how to add Jar file in android project ?

First of all download your jar file which you want to attach with your project

then right click on your project and select properties



Then select Java Build Path from left panel 




Then Select Libraries from up panel and click on Add External JARs...



Select your jar file and click Open



Now you can see that jar file is added in your project now click Ok


Thats it...share if you like or this tutorial is help you..




SharedPreferences Between two Activity

Create One class with name AppPreferences

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class AppPreferences {
 private static final String APP_SHARED_PREFS = "com.chirag.saga.password"; 
 private SharedPreferences appSharedPrefs;
 private Editor prefsEditor;

 public AppPreferences(Context context) {
  this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS,
    Activity.MODE_PRIVATE);
  this.prefsEditor = appSharedPrefs.edit();
 }

 public String getPassword() {
  return appSharedPrefs.getString("password", "0000");
 }

 public void savePassword(String text) {
  prefsEditor.putString("password", text);
  prefsEditor.commit();
 }
}

Then in your Activity...

protected AppPreferences appPrefs;
appPrefs = new AppPreferences(getApplicationContext());

and
String someString = appPrefs.getPassword();
or
appPrefs.savePassword(someString);

Tuesday, March 20, 2012

How to show html page from asserts


mWebView.loadUrl("file:///android_asset/main.html");
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.setScrollContainer(false);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSaveFormData(true);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.addJavascriptInterface(new JavaScriptInterface(this),"Android");
mWebView.setWebChromeClient(new WebChromeClient() 
{
 // Show javascript logs in LogCat
 public void onConsoleMessage(String message, int lineNumber,String sourceID) 
 {
  Log.d("MyApplication", message + " -- From line " + lineNumber + " of " + sourceID);
 }

});

Monday, March 19, 2012

WHAT IS ANDROID ?


         Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.


Features
  • Application framework enabling reuse and replacement of components
  • Dalvik virtual machine optimized for mobile devices
  • Integrated browser based on the open source WebKit engine
  • Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
  • SQLite for structured data storage
  • Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
  • GSM Telephony (hardware dependent)
  • Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
  • Camera, GPS, compass, and accelerometer (hardware dependent)
  • Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE

Android Architecture


The following diagram shows the major components of the Android operating system. Each section is described in more detail below.

Applications

Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.


Application Framework
By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.
Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.
Underlying all applications is a set of services and systems, including:
  • A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser
  • Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data
  • Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
  • Notification Manager that enables all applications to display custom alerts in the status bar
  • An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack
Libraries
Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:
  • System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices
  • Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
  • Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
  • LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view
  • SGL - the underlying 2D graphics engine
  • 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
  • FreeType - bitmap and vector font rendering
  • SQLite - a powerful and lightweight relational database engine available to all applications

Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.
The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.
Linux Kernel
Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

Load image from Link

Load image from link to ImageView.

Bitmap bitmap = BitmapFactory
    .decodeStream((InputStream) new URL(
      "http://www.diwaliwallpapers.com/images/wmwallpapers/Bhagwan-Swaminarayan-1.jpeg")
      .getContent());
    
    img.setImageBitmap(bitmap);
// where img is ImageView


Don't Forgot to add permission in manifest file like this

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

Hide the notification bar

Write this on your OnCreate() methode



getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

Saturday, March 17, 2012

Get Screen Size Of Device


get screen size of device

int windowHeight = getWindowManager().getDefaultDisplay().getHeight();
int windowWidth = getWindowManager().getDefaultDisplay().getWidth();

Generate Random No


generate Random no

Random randfact = new Random();
  Toast.makeText(getBaseContext(), "random no : "+ randfact.nextInt(10000), Toast.LENGTH_LONG).show();

On Text Changed of EditText


on Text changed of Edit text

// on Text changed of Edit text 
 mEditText.addTextChangedListener(new TextWatcher(){
               public void afterTextChanged(Editable s) {
                Log.i("TextChanges","After textChanged");
                               }
   @Override
   public void beforeTextChanged(CharSequence s, int start, int count,
     int after) {
    // TODO Auto-generated method stub
    Log.i("TextChanges", "before Text Changed");

   }

   @Override
   public void onTextChanged(CharSequence s, int start, int before,
     int count) {
    // TODO Auto-generated method stub
    Log.i("TextChanges", "On Text changed");
    
   }
           });

Date into Day tutorial


convert date into day

SimpleDateFormat inFormat = new SimpleDateFormat("dd-MM-yyyy");
  Date date = inFormat.parse(Yourdate);
  SimpleDateFormat outFormat = new SimpleDateFormat("EEEE");
  String goal = outFormat.format(date); 

Internet Connection check tutorial

How to check Internet Connection in android phone

boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
 //we are connected to a network
 connected = true;
}
else
 connected = false;

Friday, March 16, 2012

lifecycle events of Android Activity tutorial


<?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"
    >
    <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
      <TextView
            android:id="@+id/uname"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="@string/Uname">
      </TextView>
      <EditText
            android:id="@+id/utextbox"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
      </EditText>
    </LinearLayout>
    <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
      <TextView
            android:id="@+id/pass"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="@string/Pass">
      </TextView>
      <EditText
            android:id="@+id/ptextbox"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:password="true">
      </EditText>
    </LinearLayout>
    <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center">
      <Button
            android:id="@+id/login"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="@string/Login">
      </Button>
      <Button
            android:id="@+id/clear"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="@string/Clear">
      </Button>
    </LinearLayout>
   
</LinearLayout>

<?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"
  android:id="@+id/mainLayout"
  android:gravity="center">
      <TextView
             android:id="@+id/welcomeNote"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Welcome !!"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:gravity="center">
</TextView>
      <Button
            android:id="@+id/setting"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="@string/setting"
            android:textSize="20dp"
            android:gravity="center">
</Button>
     
</LinearLayout>






<?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"
  android:gravity="center">
    <TextView
      android:layout_width="wrap_content"
      android:text="@string/msg"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceLarge"
      android:id="@+id/cs"
      android:textSize="30dp"
      android:gravity="center"
      android:textColor="@color/yellow">
    </TextView>    
</LinearLayout>



Extra Files :


strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Ex1Activity!</string>
    <string name="app_name">Ex1</string>
    <string name="Uname">User Name : </string>
    <string name="Pass">Password : </string>
    <string name="Login">Login</string>
    <string name="Clear">Clear</string>
    <string name="WelcomeNote">Welcome </string>
    <string name="setting">Setting</string>
    <string name="msg">Coming Soon...</string>
</resources>



color.xml 


<?xml version="1.0" encoding="UTF-8"?>
<resources>
        <color name="yellow">#FFFF00</color>      
</resources>


Ex1Activity.java

package com.exc.first;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Ex1Activity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
      //read component from xml file
        Button login = (Button)findViewById(R.id.login);
       
      /**
       * set OnClickListener on button
       * so that code which is in between { } is run on click on login button
       */
        login.setOnClickListener(new OnClickListener() {
                 
                  @Override
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                       
                        /**
                         * make Intent to call other activity
                         * here Ex1Activity.this to go second.class
                         * on click login button
                         */
                        Intent SecAct = new Intent(Ex1Activity.this,second.class);
                       
                        //start second activity
                        startActivity(SecAct);
                       
                  }
            });
       
       
    }
    @Override
      protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            /**
             * it show massage on LogCat when Activity starts
             */
            Log.i("Login Activity", "Start");
      }
     
      @Override
      protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            /**
             * It show massage on LogCat when Activity OnPause
             */
            Log.i("Login Activity", "Pause");
      }
      @Override
      protected void onRestart() {
            // TODO Auto-generated method stub
            super.onRestart();
            /**
             * it show massage on LogCat when Activity onRestart
             */
            Log.i("Login Activity", "Restart");
      }
      @Override
      protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            /**
             * it show massage on LogCat when Activity OnResume
             */
            Log.i("Login Activity", "Resume");
      }
     
      @Override
      protected void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
            /**
             * it show massage on LogCat when Activity Stop
             */
            Log.i("Login Activity", "Stop");
      }
      @Override
      protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            /**
             * it show massage on LogCat when Activity Destroys
             */
            Log.i("Login Activity", "Destroy");
      }
}

second.java 




package com.exc.first;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class second extends Activity{

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.second);
           
            //read button from xml file
            Button setting =(Button)findViewById(R.id.setting);
            setting.setOnClickListener(new OnClickListener() {
                 
                  @Override
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                       
                        Intent goToSetting = new Intent(second.this,setting.class); //go to third Activity
                        startActivity(goToSetting);                    
                  }
            });
           
      }
      @Override
      protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            /**
             * it show massage on LogCat when Activity starts
             */
            Log.i("Second Activity", "Start");
      }
     
      @Override
      protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            /**
             * it show massage on LogCat when Activity on pause
             */
            Log.i("Second Activity", "Pause");
      }
      @Override
      protected void onRestart() {
            // TODO Auto-generated method stub
            super.onRestart();
            /**
             * it show massage on LogCat when Activity Restart
             */
            Log.i("Second Activity", "Restart");
      }
      @Override
      protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            /**
             * it show massage on LogCat when Activity Resume
             */
            Log.i("Second Activity", "Resume");
      }
     
      @Override
      protected void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
            /**
             * it show massage on LogCat when Activity  stop
             */
            Log.i("Second Activity", "Stop");
      }
      @Override
      protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            /**
             * it show massage on LogCat when Activity Destroy
             */
            Log.i("Second Activity", "Destroy");
      }

}


setting.java



package com.exc.first;

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

public class setting extends Activity {

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.setting);
           
           
      }
      @Override
      protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            /**
             * it show massage on LogCat when Activity starts
             */
            Log.i("Third Activity", "Start");
      }
     
      @Override
      protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            /**
             * it show massage on LogCat when Activity Pause
             */
            Log.i("Third Activity", "Pause");
      }
      @Override
      protected void onRestart() {
            // TODO Auto-generated method stub
            super.onRestart();
            /**
             * it show massage on LogCat when Activity Restarts
             */
            Log.i("Third Activity", "Restart");
      }
      @Override
      protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            /**
             * it show massage on LogCat when Activity Resume
             */
            Log.i("Third Activity", "Resume");
      }
     
      @Override
      protected void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
            /**
             * it show massage on LogCat when Activity stop
             */
            Log.i("Third Activity", "Stop");
      }
      @Override
      protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            /**
             * it show massage on LogCat when Activity Destroy
             */
            Log.i("Third Activity", "Destroy");
      }
}



and don't forget to enter entry of your new java file into manifest file



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exc.first"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Ex1Activity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".second"
                  android:label="@string/app_name">
           
        </activity>
        <activity android:name=".setting"
                  android:label="@string/app_name">
           
        </activity>

    </application>
</manifest>

Output



Custom Seekbar Tutorial


seekbar_progress_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <clip >
            <bitmap
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:antialias="true"
                android:dither="false"
                android:filter="false"
                android:gravity="left"
                android:src="@drawable/green">
             </bitmap>
        </clip>
    </item>
</layer-list>



seekbar_progress.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@android:id/background">
         <nine-patch
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:dither="true"
            android:src="@drawable/whitepatch">
          </nine-patch>
    </item>
    <item android:id="@android:id/secondaryProgress">
           <clip >
               <shape >
                  <gradient
                    android:angle="270"
                    android:centerColor="#80127fb1"
                    android:centerY="0.75"
                    android:endColor="#a004638f"
                    android:startColor="#80028ac8">
                   </gradient>
              </shape>
           </clip>
     </item>
     <item
             android:id="@android:id/progress"
             android:drawable="@drawable/seekbar_progress_bg">
     </item>
</layer-list>





XML

<SeekBar
                                android:id="@+id/seekbar_bar"
                                style="?android:attr/progressBarStyleHorizontal"
                                android:layout_width="420dip"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="0dip"
                                android:layout_marginTop="12dip"
                                android:maxHeight="9dp"
                                android:minHeight="9dp"
                                android:progressDrawable="@drawable/seekbar_progress"
                                android:thumb="@drawable/shine_btn" />

green.png

shine_btn.png
whitepatch.9.png

Where did Sachin Tendulkar score his 100 centuries?

Thursday, March 15, 2012

AutoCompleteTextView Tutorial


here is the layout xml file:
<AutoCompleteTextView
                        android:id="@+id/AndroidBooks"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content" >
                    </AutoCompleteTextView>
Nothing special. It just consists of one element.
Now in the main activity, I create an array of android books:
String[] androidBooks =
           {
           "Hello, Android - Ed Burnette",
           "Professional Android 2 App Dev - Reto Meier",
           "Unlocking Android - Frank Ableson",
           "Android App Development - Blake Meike",
           "Pro Android 2 - Dave MacLean",
           "Beginning Android 2 - Mark Murphy",
           "Android Programming Tutorials - Mark Murphy",
           "Android Wireless App Development - Lauren Darcey",
           "Pro Android Games - Vladimir Silva",
           };
Then in the onCreate(..) method, I create an ArrayAdapter that I can pass to thisAutoCompleteTextView as the data Source.

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


Then, I get a handle to the AutocompleteTextView, and set the arrayAdapter to it along with the Threshold. The Threshold defines the number of charaters a user should type before the suggestions start showing up.

AutoCompleteTextView acTextView = (AutoCompleteTextView)findViewById(R.id.acTVCountry);
           acTextView.setThreshold(3);
           acTextView.setAdapter(adapter);
That is it. Now execute and see it work. 

This is the way it would look: