Tuesday, 20 March 2012

Android Custom Alert Dialog

                                     Android Custom Alert Dialog

 1) AlertDialog is a small window that appears or pop up in front of your application.
 2) It gets the screen focus and able to accept user interaction.
 3) Dialogs are normally used for notifications that should interrupt the user and to perform short tasks.

Step 1:

Create a new project as CustomAlertDialog.
Copy  the below coding and paste it into your main.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:orientation="vertical" >

  <Button
        android:id="@+id/btn_alert"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Alert Dialog" />

</LinearLayout>

Step 2:

Copy the below code and paste into your java file(CustomAlertDialog.java).


package com.custom.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CustomDialog extends Activity {
    Button buttonAlert;

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

        buttonAlert = (Button) this.findViewById(R.id.btn_alert);
        buttonAlert.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(CustomDialog.this);
                alertBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener()                            {
                            public void onClick(DialogInterface dialog, int id) {
                                // If press the OK button if finishes the dialog.
                             }
                        });

                AlertDialog alert = alertBuilder.create();
           
                alert.setIcon(R.drawable.ic_launcher);
                alert.setTitle("Alert Title");
                alert.setMessage("Alert Message");
                alert.show();
            }
        });
    }
}



Full Source code for CustomAlertDialog

Android Custom Toast Tutorial

                                     Android Custom Toast



1) Toast is used to show simple message to the user.
2) Toast doesn't take focus,and not having interaction.
3) Based on the text size, the toast occupy the space in a screen.
4) By default it displays in bottom of the device.

Step 1:

Copy the below xml file and paste it in main.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:orientation="vertical" >

    <Button
        android:id="@+id/btn_short_toast"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Short Toast" />

    <Button
        android:id="@+id/btn_long_toast"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Long Toast" />

    <Button
        android:id="@+id/btn_custom_toast"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Custom Toast" />

</LinearLayout>

Step 2:

Create the custom_toast.xml file in layout folder. Then copy the below coding and paste in custom_toast.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_layout_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ff9977"
    android:orientation="horizontal"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/toast_image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="5dp"
       android:background="@drawable/ic_launcher"/>

    <TextView
        android:id="@+id/text_toast_message"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#00ffff"
        android:text="Custom Toast"
      />

</LinearLayout>

Step 3:

Here is the  CustomToastExample.java.Copy and paste the java coding into your project.

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CustomToastExample extends Activity {
    Button shortToast, longToast, customToast;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        shortToast = (Button) this.findViewById(R.id.btn_short_toast);
        longToast = (Button) this.findViewById(R.id.btn_long_toast);
        customToast = (Button) this.findViewById(R.id.btn_custom_toast);

        shortToast.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Show for 3 seconds",
                        Toast.LENGTH_SHORT).show();
            }
        });
       
        longToast.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Show for 5 seconds",
                        Toast.LENGTH_LONG).show();
            }
        });
       
        customToast.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                LayoutInflater inflater = getLayoutInflater();

                View layout = inflater.inflate(R.layout.custom_toast,
                        (ViewGroup) findViewById(R.id.custom_toast_layout_id));

                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
                toast.show();
            }
        });
    }
}






The complete Source code for Custom Toast Sample

Tuesday, 13 March 2012

Android Button State

                                                       Button State In Android

Here I post how to change the buttons background based on it's state.

At the end of this tutorial i post the full source code. In that you can get button background images.
This is the simple sample code, follow my instructions.


Step 1:
 Create new folder as "drawable" in res folder.In that folder create new "select.xml"  file and paste the below coding.

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

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pressed_select" android:state_pressed="true" />
    <item android:drawable="@drawable/focused_select" android:state_focused="true" />
    <item android:drawable="@drawable/normal_select" />
</selector>

Step 2:
Copy the below coding and paste it to main.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:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/select" />
</LinearLayout>

Step 3:
This is the defalut java class.You may use or may not use.

import com.control.state.R;
import android.app.Activity;
import android.os.Bundle;

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

Step 4:
 Now run the program now you got output,
a) First the button is in normal state(white color).
b) Scroll the mouse , now it is focused state(light green).
c) Click the button, now it is in pressed state(orange color).

normal_state
focused_state
pressed_state

Full Source code for ButtonState

Monday, 12 March 2012

Android Emulator Shortcuts

                        Android Simple Emulator Shortcuts  

  Here i post some of the useful android emulator shortcuts.
 Use this shortcuts,it makes you perfect android developer.
 

Main Device Keys

Home                 Home Button
F2 Left Softkey / Menu / Settings button (or page up)
Shift+f2 Right Softkey / Star button (or page down)
Esc Back Button
F3 Call/ dial Button
F4 Hang up / end call button
F5 Search Button







Other Device Keys

Ctrl+F5               Volume up (or + on numeric keyboard with Num Lock off)
Ctrl+F6 Volume down (or + on numeric keyboard with Num Lock off)
f7 Power Button
Ctrl+F3 Camera Button
Ctrl+F11 Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
F8 Toggle cell network
F9 Toggle code profiling
Alt+Enter Toggle fullscreen mode
F6 Toggle trackball mode

Android Shortcuts


                     Android keyboard Shortcuts


Scrolling
Spacebar: Page down in any Web page/document view
Shift + Spacebar: Page up in any Web page/document view

 Typing
Alt + Spacebar: Insert a special character
Shift + Del: Delete the character to the right of the cursor
Alt + Del: Delete an entire line
Shift + Shift (press it twice): Activate caps-lock; press shift once more to exit
Alt + Trackball-Left: Move cursor to beginning of line
Alt + Trackball-Right: Move cursor to end of line
Alt + Trackball-Up: Move cursor to top of page
Alt + Trackball-Down: Move cursor to bottom of page
Shift + Trackball-Left/Right: Highlight text for cutting or copying
Menu + X: Cut text (will cut all text on-screen unless specific characters are highlighted)
Menu + C: Copy text to clipboard (will copy all text on-screen unless specific characters are highlighted)
Menu + V: Paste text from clipboard
Menu + A: Select all text in the current field

Browsing
Menu + I: Zoom in
Menu + O: Zoom out
Menu + J: Go back a page
Menu + K: Go forward a page
Menu + R: Refresh current page
Menu + F: Find on page
Menu + B: Open bookmarks
Menu + S: Open social network sharing menu
Menu + H: View browsing history
Menu + S: Open browser settings

 Gmail
F: Forward current message (works only while inside the message)
R: Reply to current message (works only while inside the message)
A: Reply-all to current message (works only while inside the message)
Y: Archive message (works from within message or while on main inbox list)
Menu + U: Refresh inbox
Menu + C: Compose new e-mail
Enter: Open an e-mail (from the main inbox list)
Alt + Trackball-Up: Jump to top of inbox
Alt + Trackball-Down: Jump to bottom of inbox
Android Keyboard Shortcuts: Apps
Search + B: Open browser
Search + C: Open contacts
Search + E: Open e-mail
Search + G: Open Gmail
Search + I: Open calendar
Search + M: Open maps
Search + P: Open music
Search + S: Open text messaging
Search + Y: Open YouTube

Important Android Codes

     
                                                Android secret codes


DISCLAIMER: This information is intended for experienced users. It is not intended for basic users, hackers, or mobile thieves. Please do not try any of following methods if you are not familiar with mobile phones. We'll not be responsible for the use or misuse of this information, including loss of data or hardware damage. So use it at your own risk.
*#*#4636#*#*
This code can be used to get some interesting information about your phone and battery. It shows following 4 menus on screen:
*#*#7780#*#*
This code can be used for a factory data reset. It'll remove following things:
  • Google account settings stored in your phone
  • System and application data and settings
  • Downloaded applications
It'll NOT remove:
  • Current system software and bundled applications
  • SD card files e.g. photos, music files, etc.
PS: Once you give this code, you get a prompt screen asking you to click on "Reset phone" button. So you get a chance to cancel your operation.
*2767*3855#
Think before you give this code. This code is used for factory format. It'll remove all files and settings including the internal memory storage. It'll also reinstall the phone firmware.
PS: Once you give this code, there is no way to cancel the operation unless you remove the battery from the phone. So think twice before giving this code.
*#*#34971539#*#*
This code is used to get information about phone camera. It shows following 4 menus:
  • Update camera firmware in image (Don't try this option)
  • Update camera firmware in SD card
  • Get camera firmware version
  • Get firmware update count
WARNING: Never use the first option otherwise your phone camera will stop working and you'll need to take your phone to service center to reinstall camera firmware.
*#*#7594#*#*
This one is my favorite one. This code can be used to change the "End Call / Power" button action in your phone. Be default, if you long press the button, it shows a screen asking you to select any option from Silent mode, Airplane mode and Power off.
You can change this action using this code. You can enable direct power off on this button so you don't need to waste your time in selecting the option.
*#*#273283*255*663282*#*#*
This code opens a File copy screen where you can backup your media files e.g. Images, Sound, Video and Voice memo.
*#*#197328640#*#*
This code can be used to enter into Service mode. You can run various tests and change settings in the service mode.
WLAN, GPS and Bluetooth Test Codes:
*#*#232339#*#* OR *#*#526#*#* OR *#*#528#*#* - WLAN test (Use "Menu" button to start various tests)
*#*#232338#*#* - Shows WiFi MAC address
*#*#1472365#*#* - GPS test
*#*#1575#*#* - Another GPS test
*#*#232331#*#* - Bluetooth test
*#*#232337#*# - Shows Bluetooth device address
*#*#8255#*#*
This code can be used to launch GTalk Service Monitor.

Codes to get Firmware version information:
*#*#4986*2650468#*#* - PDA, Phone, H/W, RFCallDate
*#*#1234#*#* - PDA and Phone
*#*#1111#*#* - FTA SW Version
*#*#2222#*#* - FTA HW Version
*#*#44336#*#* - PDA, Phone, CSC, Build Time, Changelist number

Codes to launch various Factory Tests:
*#*#0283#*#* - Packet Loopback
*#*#0*#*#* - LCD test
*#*#0673#*#* OR *#*#0289#*#* - Melody test
*#*#0842#*#* - Device test (Vibration test and BackLight test)
*#*#2663#*#* - Touch screen version
*#*#2664#*#* - Touch screen test
*#*#0588#*#* - Proximity sensor test
*#*#3264#*#* - RAM version
NOTE: All above codes have been checked on Google Android phone Samsung Galaxy I7500 only but they should also work in other Google Android phones.


                                      


Friday, 9 March 2012

Share Data Across Application in Android

                      Share Data Across Application in android using Shared Preference


* Android allow us to share data across applications.
* Context.MODE_WORLD_READABLE is important thing in shared preference for global data access.

* Run both project in the same emulator, Follow the below steps,


Step 1:

Create the android application name as "SharedPref1"

Package name as "com.sharepref1"

Copy the below code and paste it in main.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" >

    <EditText
        android:id="@+id/edit_share_value"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_share_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share Data" />

</LinearLayout>


Copy the below code and paste it in your java class(SharedPref1Activity).

package com.sharedpref1;

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

public class SharedPref1Activity extends Activity {
    EditText editShareValue;
    Button btnShareValue;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnShareValue = (Button) this.findViewById(R.id.btn_share_value);
        editShareValue = (EditText) this.findViewById(R.id.edit_share_value);

        btnShareValue.setOnClickListener(new OnClickListener() {

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

                String strShareValue = editShareValue.getText().toString()
                        .trim();
                SharedPreferences prefs = getSharedPreferences("demopref",
                        Context.MODE_WORLD_READABLE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("demostring", strShareValue);
                editor.commit();

            }
        });
    }
}







save and run the program ,enter any data and click Share Data button.



Step 2:
Create the android application name as "SharedPref2"

Package name as "com.sharepref2"

Copy the below code and paste it in main.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" >

    <TextView
        android:id="@+id/text_display_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/btn_display_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Value" />

</LinearLayout>


Copy the below code and paste it in your java class(SharedPref2Activity).


package com.sharedpref2;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SharedPref2Activity extends Activity {
    TextView displaySharedValue;
    Button displayValue;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        displaySharedValue = (TextView) this
                .findViewById(R.id.text_display_value);
        displayValue = (Button) this.findViewById(R.id.btn_display_value);
        displayValue.setOnClickListener(new OnClickListener() {

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

                    con = createPackageContext("com.sharedpref1", 0);
                    SharedPreferences pref = con.getSharedPreferences(
                            "demopref", Context.MODE_PRIVATE);
                    String data = pref.getString("demostring", "No Value");
                    displaySharedValue.setText(data);
                } catch (NameNotFoundException e) {
                    Log.e("Not data shared", e.toString());
                }
            }
        });

    }
}

save and run the program in the same emulator which you run the first one.


Now click DisplayValue button.Now you get the data which you entered in sharedpref1.

Full source code SharedPref

Screen Orientation in Android

                                      Support Screen Orientation in Android



Android project defaultly having main.xml file in layout folder. It supports both portrait and landscape.
But some times our layout is not aligned well when skip to landscape mode.
So we cannot able to get an expected view.Ex: textview ,button are misplaced.
We can overcome this problem by using "layout-land" folder in our application.

Step 1:

Copy the below code and paste it in main.xml file which is in layout folder.

<?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" android:gravity="center">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Portrait"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:gravity="center"/>

  </LinearLayout>

Step 2:
Create a "layout-land" folder in res folder.That is

res ->rightclick ->new ->folder-> name the folder name as "layout-land"

Step 3:
create a main.xml file in "layout-land" folder.Then Copy the below code and paste it in main.xml file which is in layout-land folder.

<?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" android:gravity="center">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LandScape"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:gravity="center"/>

</LinearLayout>

Now run your program it will produce a result as

Portrait mode(default)


While changing to landscape (ctrl+f12) will produce a result as



Thank you.

Full Source code Screen Orientation

Friday, 2 March 2012

Android Project Structure

 

           
src/
     Contains package folder which having all our java files.
gen/
     This contains the Java files generated by ADT, such as your R.java file and interfaces created from AIDL files.
Android jar/
     Based on the version  you choose, it takes android jar file.
     This jar file contains all its default android package with it.
assets/
     This is empty. You can use it to store raw asset files.
     If you want to use some new font style you can put .ttf file here.
 bin/
     The bin folder contains our project’s apk file.
     When running our project, the apk file uploaded in emulator for execution then show the output.
res/
     A folder for your application resources, the list below
 * Animator/
    It starts from 3.0 , used to animate properties of any object   it is more flexible and offers  more features
    * anim/
        Used to  perform a series of simple transformations like position, size, rotation, and transparency.
    * color/
    Used to change the color based on the state like pressed,focused.
    * drawable/
    Used to store image files like .png, .9.png, .jpg, .gif.
    * layout/
       It is a xml file which contains all our UI designs.
    * menu/
        XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu.
    * raw/
        Arbitrary files to save in their raw form . Used to store sound files.
        *  values/
        XML files that contain simple values, such as strings, integers, and colors.
 
AndroidManifest.xml 
    This is the first file execute in android application. 
    This contains important info about our application. 
    Some of the manifest tags are listed below,

<uses-permission/> - Allow permission for accessing additional things(ie: internet).
<application/>         - Our app name , icon ,<activity><service><receiver><provider>tags.
<activity/>               - particular activity properties <intent-filter><meta-data>
<instrumentation/>   - Used for testing purposes of our android projects
<supports-screens/>- Used to support multiple screens.
<uses-library/>        - some app need library to add like google mapview.  And so on.

default.properties
     This file contains project settings, such as the build target. This file is integral to the project, as such, it should be maintained in a Source Revision Control system. It should never be edited manually — to edit project properties, right-click the project folder and select "Properties".

Thursday, 1 March 2012

Android Naming Conventions

                         



The android naming convention is same as java naming convertion.

This Naming conventions are very important thing to follow while develop best android applications.

Four things we need to concentrate while naming in android

1) Wheather it is a noun or verb.
2) Proper use of Characters.
3) No empty spaces are allowed.
4) Avoid using dollar($) symbol.

Package    * Package name should be noun
                   * Package name should be lowercase letters
                   * Package name must be seperated with periods(.dot)

Example:   com.android.shopping
                 com.bank.account

Class        * Class name should be noun
                 * Class name should Initcap.
       
Example:   AccountHolder, AccountType


Interface    * interface name should be noun.
                   * interface name should Initcap.

Example:    DataHelper, AccountName

Method     * method name should be verb.
                  * starts with lowercase continue with InitCap

Example:    processAccount(), getUserDetail(), diaplayUserDetails()

Variable       *Variable name should be Meaningful and verb.
                     * starts with lowercase continue with InitCap
                     * for local variables like for , while can use lowercase(i,j,k).
                     * Allow dollar($),underscore(_)symbols.underscore is always recommended.

Example:    buttonSubmit, edit_Text_UserName,  _strTotal

Constant           * Constants always in uppercase
                         *  Underscore(_) is permittable

Example:    HEAD_COUNT, MAXIMUM_SIZE


Control Structure


Even for single line statement we need to surround by block {}.This is for best practice.

Example:

Poor usage
        if(true)
        Statement;

Good usage
        if(true)
        {
        Statement;
        }

Comments 

  Put comments before doing anything in program. It make us better understanding when see it again.