Monday, August 26, 2013

Custom ListView Example

This is a tutorial about customizing listview with and image and text.

Download Source Code for FREE:Here


Creating New Project

  • Create New Project in Eclipse. File => New Project.
  • Create New folder in res named drawable.
  • Create New gradient_bg.xml file in drawable directory and fill with following code. It is used to set gradient background in listView.

gradient_bg.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#424242"
      android:centerColor="#585858"
      android:endColor="#6E6E6E"
      android:angle="270" />
</shape>


  • Create New gradient_bg_hover.xml file in drawable directory and fill with following code. It is used to set gradient background when listView item is pressed.

 gradient_bg_hover.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#8A0808"
      android:centerColor="#610B0B"
      android:endColor="#B40404"
      android:angle="270" />
</shape>

  • Create New list_main.xml file in drawable directory and fill with following code. It is used to integrate above files into listView..

list_main.xml


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

  • Now add following code into activity_main.xml file.

activity_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">
    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#2A0A12"
        android:dividerHeight="2dp"
        android:listSelector="@drawable/list_main" />
</LinearLayout>

  • Next step is to design single row of listView. Create New xml file in layout directory and name it as row_layout.xml.

row_layout.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="wrap_content"
    android:background="@drawable/list_main"
    android:orientation="horizontal"
    android:padding="5dip" >


    <LinearLayout
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip"
        android:padding="3dip" >

        <ImageView
            android:id="@+id/list_image"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

   

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Country name"
        android:textColor="#FFFFFF"
        android:textSize="15dip"
        android:textStyle="bold"
        android:typeface="sans" />

</RelativeLayout>

  • Until now we completed designing part of the listView. Next step is to add content in listview with different images. Add following code in MainActivity.java file. 

MainActivity.java



public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String listArray[] = new String[] { "India", "England", "Canada",
"New zealand", "South Africa", "Pakistan", "West indies" };
int icon[] = new int[] { R.drawable.india, R.drawable.england,
R.drawable.canada, R.drawable.new_zealand,
R.drawable.south_africa, R.drawable.pakistan,
R.drawable.west_indies };

ListView listView = (ListView) findViewById(R.id.listView);
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

for (int i = 0; i <= listArray.length - 1; i++) {

HashMap<String, String> hm = new HashMap<String, String>();
hm.put("title", listArray[i]);
hm.put("icon", Integer.toString(icon[i]));
aList.add(hm);
}

String[] sfrm = { "title", "icon" };
int[] sto = { R.id.title, R.id.list_image };

SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList,
R.layout.row_layout, sfrm, sto);

listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {

switch (position) {

case 0:
Toast.makeText(getApplicationContext(), "India",
Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "England",
Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Canada",
Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "New zealand",
Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(getApplicationContext(), "South Africa",
Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(getApplicationContext(), "Pakistan",
Toast.LENGTH_SHORT).show();
break;
case 6:
Toast.makeText(getApplicationContext(), "West Indies",
Toast.LENGTH_SHORT).show();
break;

}

}
});
}
}

  • Done !

Download Source Code for FREE:Here



Wednesday, August 21, 2013

Rating Bar Full Example

activity_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"
    >
    
    <RatingBar android:id="@+id/rating_1"
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="3"
        android:rating="2.5">
    </RatingBar>
    
    <RatingBar android:id="@+id/rating_2"
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="2.25">
    </RatingBar>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip">
    
<TextView  
android:id="@+id/rating"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
   
    <RatingBar android:id="@+id/small_ratingbar"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_marginLeft="5dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical" />
    </LinearLayout>
    
    <RatingBar android:id="@+id/indicator_ratingbar"
        style="?android:attr/ratingBarStyleIndicator"
        android:layout_marginLeft="5dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" 
        />
        
</LinearLayout>



MainActivity.java



public class MainActivity extends Activity implements RatingBar.OnRatingBarChangeListener
{
RatingBar mSmallRatingBar;
RatingBar mIndicatingRatingBar;
TextView mRatingText;
    /** Called when the activity is first created. */
   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mRatingText=(TextView)findViewById(R.id.rating);
        
        mSmallRatingBar=(RatingBar)findViewById(R.id.small_ratingbar);
        mIndicatingRatingBar=(RatingBar)findViewById(R.id.indicator_ratingbar);
        
        ((RatingBar)findViewById(R.id.rating_1)).setOnRatingBarChangeListener(this);
        ((RatingBar)findViewById(R.id.rating_2)).setOnRatingBarChangeListener(this);
    }
    
   
    public void onRatingChanged(RatingBar ratingBar,float rating,boolean fromTouch)
    {
    final int numStars=ratingBar.getNumStars();
   
    mRatingText.setText(getString(R.string.ratingbar_rating)+" "+rating+" / "+numStars);
   
    if(mIndicatingRatingBar.getNumStars()!=numStars)
    {
    mIndicatingRatingBar.setNumStars(numStars);
    mSmallRatingBar.setNumStars(numStars);
    }
   
    if(mIndicatingRatingBar.getRating()!=rating)
    {
    mIndicatingRatingBar.setRating(rating);
    mSmallRatingBar.setRating(rating);
    }
   
    final float ratingBarStepSize=ratingBar.getStepSize();
   
    if(mIndicatingRatingBar.getStepSize()!=ratingBarStepSize)
    {
    mIndicatingRatingBar.setStepSize(ratingBarStepSize);
    mSmallRatingBar.setStepSize(ratingBarStepSize);
    }
    }

}



Drag and Drop Example

Drag and Drop is useful in canvas or drawing application.Here is full description,just follow it.


  • Modify the code in activity_main.xml file.

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Drag Me" >
    </Button>

</FrameLayout>


  • Add below code in MainActivity.java file.

MainActivity.java



public class Home extends Activity implements OnTouchListener {


private final static int START_DRAGGING = 0;
private final static int STOP_DRAGGING = 1;

private Button btn;
private FrameLayout layout;
private int status;
private LayoutParams params;

private ImageView image;

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

layout = (FrameLayout) findViewById(R.id.LinearLayout01);
// layout.setOnTouchListener(this);

btn = (Button) findViewById(R.id.btn);
btn.setDrawingCacheEnabled(true);
btn.setOnTouchListener(this);

params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);

}

@Override
public boolean onTouch(View view, MotionEvent me) 
{
if (me.getAction() == MotionEvent.ACTION_DOWN) {
status = START_DRAGGING;
image = new ImageView(this);
image.setImageBitmap(btn.getDrawingCache());
layout.addView(image, params);
}
if (me.getAction() == MotionEvent.ACTION_UP) {
status = STOP_DRAGGING;
Log.i("Drag", "Stopped Dragging");
} else if (me.getAction() == MotionEvent.ACTION_MOVE) {
if (status == START_DRAGGING) {
System.out.println("Dragging");
image.setPadding((int) me.getRawX(), (int) me.getRawY(), 0, 0);
image.invalidate();
}
}
return false;
}
}

  • Done ! Now Run the Project.Try to drag button.

Friday, August 16, 2013

Shared Preference Example

Shared preference is used to store data globally and use it to anywhere in application. Two way we can use it.One is define global variable and other is shared preference.The main problem with global variable is data will be lost when user closes the application.To resolve this problem we can use shared preference.It maintains the data even user closes the app.


Initialization


Initialization of shared preference is given below.

SharedPreferences sp = this.getSharedPreferences("data",Activity.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();

Here,Editor is used to edit data of Shared Preference.

Store Data

Using Editor, you can store data into Shared Preference.We can use data types like boolean, string, int,float, long.Code is given below for all data types.

edit.putBoolean("enter_name",true);
edit.putString("enter_name","string_value");
edit.putInt("enter_name","int_value");
edit.putFloat("enter_name","float_value");
edit.putLong("enter_name","long_value");

edit.commit();    // Apply to store data.Don't forget to write it.

NOTE: edit.commit(); is the most important line.It is used to apply changes in shared preference.


Retrieve Data


You can retrieve Shared preference data through getString() method and so on.First of all you need to define Shared preference with same name.like:

 SharedPreferences sp = this.getSharedPreferences("data",Context.MODE_PRIVATE);

sp.getString("enter_name","default_string");
sp.getInt("enter_name",1);
sp.getBoolean("enter_name",true);
sp.getFloat("enter_name",null);
sp.getLong("enter_name",null);


Sample Code:

  • First Create 2 activities - 1. MainActivity.java    2. GetActivity.java.
  • MainActivity.java - Store data into Shared Preference.
  • GetActivity.java - Retrieve stored data.

MainActivity.java


public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sp = this.getSharedPreferences("abc",Activity.MODE_PRIVATE);
final SharedPreferences.Editor edit = sp.edit();
final EditText name = (EditText)findViewById(R.id.name);
final EditText pass = (EditText)findViewById(R.id.pass);
Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String sname =  name.getText().toString();
   String spass = pass.getText().toString();
  edit.putString("username", sname);
  edit.putString("password", spass);
  edit.commit();
}
});
Button retrive = (Button) findViewById(R.id.retrive);
retrive.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,GetActivity.class);
startActivity(intent);
}
});
}
}

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:" />

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <EditText
        android:id="@+id/pass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SAVE" />

    <Button
        android:id="@+id/retrive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Retrive Information" />

</LinearLayout>


GetActivity.java



public class GetActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get);
TextView usertv =(TextView)findViewById(R.id.usertext);
TextView passtv =(TextView)findViewById(R.id.passtext);
SharedPreferences sp = this.getSharedPreferences("abc",Context.MODE_PRIVATE);

 usertv.setText(sp.getString("username","" ));
passtv.setText(sp.getString("password", ""));
}
}


activity_get.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".GetActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Get Data" />

    <TextView
        android:id="@+id/usertext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Username" />

    <TextView
        android:id="@+id/passtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Password" />

</LinearLayout>



Download Full Source Code:  Here



Clipboard Example

Clipboard is used to copy data and paste it anywhere in android device.Only text is stored in clipboard.
Note that there are 2 different methods for clipboard.It depends on android SDK version.

  1. If SDK version is less than HONEYCOMB.
  2. SDK version is Greater or equal to HONEYCOMB SDK version.


    1. if SDK version is less than HONEYCOMB,copy below code.
    String copyData = "hi,how are u?";
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
       clipboard.setText(copyData);
       Toast.makeText(ScanActivity.this,"Text copied", Toast.LENGTH_SHORT).show();


       2.  SDK version is Greater or equal to HONEYCOMB SDK version.

    String copyData = "hi,how are u?";
     android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
       android.content.ClipData clip = android.content.ClipData.newPlainText("label",copyData);
       clipboard.setPrimaryClip(clip);

       Toast.makeText(ScanActivity.this,"Text copied", Toast.LENGTH_SHORT).show();


    Full Source Code for both version method is given below,Just copy it on your code.

    String finalData = "hi,how are u?";
    int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
       android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
       clipboard.setText(finalData);
       Toast.makeText(ScanActivity.this,"Text copied", Toast.LENGTH_SHORT).show();
    } else {
       android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
       android.content.ClipData clip = android.content.ClipData.newPlainText("label",finalData);
       clipboard.setPrimaryClip(clip);
       Toast.makeText(ScanActivity.this,"Text copied", Toast.LENGTH_SHORT).show();
    }

    Toast.makeText(getApplicationContext(), "Copy",Toast.LENGTH_SHORT).show();



    • Done ! now go to message activity, press and hold in EditText. Now past clipboard text into it.



    Thursday, August 15, 2013

    Get Phone Details of Android device

    Now you can know about your device information in just one click.Device information like: Bootloader, brand, CPU ABI, CPU ABI2, Device, Display, Fingerprint, Hardware, Manufacturer, Product, SDK Version.


    • No need to add any permissions in AndroidMenifest.xml file.

    1. android.os.Build.BOOTLOADER
    2. android.os.Build.BRAND
    3. android.os.Build.CPU_ABI
    4. android.os.Build.CPU_ABI2
    5. android.os.Build.DEVICE
    6. android.os.Build.DISPLAY
    7. android.os.Build.FINGERPRINT
    8. android.os.Build.HARDWARE
    9. android.os.Build.MANUFACTURER
    10. android.os.Build.PRODUCT
    11. android.os.Build.VERSION.SDK


    • Just set it in textView and check result. Here i have attached screenshot of this details.


    Download Full Source Code: Here




    Get SIM card details

    Get SIM card details through code. Here is full description of all SIM cards.


    • Add two permissions in AndroidMenifest.xml file.It is necessary to access phone state and network state. 

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

    • To use Telephone service first of all you need to define it in onCreate() method- MainActivity.java.
    TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

    • Use tm object and find below all functions.

    1. tm.getLine1Number()   -  Get SIM card Number
    2. tm.getSimSerialNumber()   -   Get SIM Serial Number
    3. tm.getSimOperatorName()   - Get SIM operator name
    4. tm.getDeviceId()   - IMEI Number of device
    5. tm.getDeviceSoftwareVersion()   - Device software Version
    6. tm.getNetworkCountryIso()   -   Network Country code
    7. tm.getNetworkOperator()   -  SIM Network operator number 
    8. tm.getSubscriberId()   -  Subscriber Id
    9. tm.getVoiceMailNumber() - Get VoiceMail Number
    10. tm.getSimCountryIso()   -  SIM Country code
    11. tm.getSimOperator()   - SIM Operator name
    12. tm.isNetworkRoaming()   -  Check currently your SIM has Roaming service(return boolean)
    13. tm.getPhoneType()   - Phone Type - (return int-> 0-None,1-GSM,2-CDMA,3-SIP,4-Unknown) 
    14. tm.getDataState() - GPRS Status(return int -> 0-disconnected,1-connecting,2-connected,3-Suspended,4-Unknown)


    Get Full Source Code: Here



    Install APK from assets in android application

    Yes, We can install another application from installed application !!!
    Sometimes our application is dependent in other application,at that time you need to store application APK file into assets folder and just write code for it. Thats it.

    The main benefit is there is no requirement of internet to download application which you need to use in your application.The question arrives in your mind is, how it is possible?
    Here is full description for that.



    • Create one folder called rar in assets folder.
    • Copy another application APK and paste it into this rar folder.   
    • Create one button or other component which is used to install APK file.
    • For Example, I choose button for install APK file.
    • Now add below code carefully in MainActivity.java


    MainActivity.java




    public class MainActivity extends Activity {


    Button b;
    String rarPath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b = (Button) findViewById(R.id.button1);

    b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

    rarPath = "rar/sms.apk";
    AssetManager assetManager = getAssets();

    InputStream in = null;
    OutputStream out = null;
    try {
       in = assetManager.open(rarPath);
       out = new FileOutputStream("/sdcard/myapk.apk");

       byte[] buffer = new byte[1024];

       int read;
       while((read = in.read(buffer)) != -1) {

           out.write(buffer, 0, read);

       }

       in.close();
       in = null;

       out.flush();
       out.close();
       out = null;

       Intent intent = new Intent(Intent.ACTION_VIEW);

       intent.setDataAndType(Uri.fromFile(new File("/sdcard/myapk.apk")),
           "application/vnd.android.package-archive");

       startActivity(intent);

    } catch(Exception e) { e.printStackTrace();
    Toast.makeText(getApplicationContext(),"Error !",Toast.LENGTH_LONG).show();}
    }
    });
    }
    }

    Done. Now run the project.

    NOTE: If APK file size is more than 2Mb, it will take some time to copy and install it.
    Use Thread or AsyncTask for heavy APK file.

    Tuesday, August 13, 2013

    Use External fonts in android App

    Tired to use default font in android application? I m here to learn you, how to use external fonts in your android application. In most of popular application uses their own fonts.It increases the UI layout and make it more attractive !!! So, are you ready to use external fonts???

    Here is the full source code for custom fonts.


    • First of all create one folder in assets package and name it : fonts
    • Insert custom font(s) in fonts folder which you wants to set in your application.
    • I have copied three custom fonts for Ex: batman.ttf, harryp.ttf, pac.TTF.
    • Add below code in activity_main.xml file.

    activity_main.xml



    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#222222"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#222222"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/bat"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Batman" />

            <Button
                android:id="@+id/pac"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Pac font" />

            <Button
                android:id="@+id/harry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="HarryPotter" />
        </LinearLayout>

        <TextView
            android:id="@+id/ghost"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="50dip"
            android:gravity="center"
            android:text="Font"
            android:textColor="#ef0000"
            android:textSize="70dip" />

    </LinearLayout>


    • Now add below code in MainActivity.java file.

    MainActivity.java


    public class MainActivity extends Activity {

    Button bat,pac,harry;
    String fontPath;
    Typeface tf;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            final TextView txtGhost = (TextView) findViewById(R.id.ghost);
            bat = (Button)findViewById(R.id.bat);
            pac = (Button)findViewById(R.id.pac);
            harry = (Button)findViewById(R.id.harry);
            
            bat.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    fontPath = "fonts/batman.ttf";
    tf = Typeface.createFromAsset(getAssets(), fontPath);
    txtGhost.setTypeface(tf);
    }
    });
            
            pac.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    fontPath = "fonts/pac.TTF";
    tf = Typeface.createFromAsset(getAssets(), fontPath);
    txtGhost.setTypeface(tf);
    }
    });
          
            harry.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    fontPath = "fonts/harryp.ttf";
    tf = Typeface.createFromAsset(getAssets(), fontPath);
    txtGhost.setTypeface(tf);
    }
    });
            
        }

    }


    • Done ! Now run this project.

    Download full Source code: Download

    Download full Source code: Download




    Spinner Demo

    We can also called as "drop down list".


    • Add below code in activity_main.xml file.

    activity.main.xml



    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:entries="@array/channel_arrays" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Go" />

    </LinearLayout>


    • Here we use the array to add text in spinner.
    • Add below array code in res > values > strings.xml file.
     <string-array name="channel_arrays">
            <item>Food - Food</item>
            <item>SAB</item>
            <item>SONY</item>
            <item>M tv</item>
            <item>Colors</item>
            <item>Star Plus</item>
            <item>Discovery</item>
            <item>Histroy</item>
        </string-array>

    • Add below code  in MainActivity.java file.

    MainActivity.java


    public class MainActivity extends Activity {

    Spinner sp;
    Button b;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sp = (Spinner)findViewById(R.id.spinner1);
    b = (Button)findViewById(R.id.button1);
    sp.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view,
    int pos, long id) {
    Toast.makeText(parent.getContext(), 
    "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
    Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
    }
    });
    b.setOnClickListener(new OnClickListener() {public void onClick(View v) {
    Toast.makeText(MainActivity.this,"OnClickListener : "+"\nSpinner 1 : "+ String.valueOf(sp.getSelectedItem()),
    Toast.LENGTH_SHORT).show();
    }
    });
    }

    }

    Text To Speech Example with source code

    Text to speech as name suggest, It speaks whatever you write !!! It's interesting. Isn't It? Now you can add this function into your application and make more downloads.... ;)

    It is very simple and less code to apply this function.Before start to integrate this function, make sure your device / emulator has support language and TTS(Text To Speech).

    Now here is full source code with steps:

    • Create one project in which you want to integrate TTS.
    • Add below code in activity_main.xml file.

    activity_main.xml



    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ffffff"
        android:orientation="vertical"
        tools:ignore="HardcodedText" >
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="15dip"
            android:text="Text To Speech"
            android:textColor="#0587d9"
            android:textSize="26dip"
            android:textStyle="bold" />
        <EditText
            android:id="@+id/txtText"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dip"
            android:layout_marginTop="20dip"
            android:hint="Enter text to speak" />
        <Button
            android:id="@+id/btnSpeak"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dip"
            android:enabled="false"
            android:text="Speak" />
    </LinearLayout>



    • Now implements OnInitListener to MainActivity and add unimplemented method.
    • add below code above onCreate method in MainActivity.java.


            private TextToSpeech tts;
    private Button btnSpeak;
    private EditText txtText;

    • Now add below code in onCreate method in MainActivity.java.
              tts = new TextToSpeech(this, this);
    // Refer 'Speak' button
    btnSpeak = (Button) findViewById(R.id.btnSpeak);
    // Refer 'Text' control
    txtText = (EditText) findViewById(R.id.txtText);
    // Handle onClick event for button 'Speak'
    btnSpeak.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
    // Method yet to be defined
    speakOut();
    }

    });



    • onInit(int status) method is automatically created.
    • add below code in it (onInit method).


    if (status == TextToSpeech.SUCCESS) {
    // Setting speech language
    int result = tts.setLanguage(Locale.US);
    // If your device doesn't support language you set above
    if (result == TextToSpeech.LANG_MISSING_DATA
    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
    // Cook simple toast message with message
    Toast.makeText(this, "Language not supported",
    Toast.LENGTH_LONG).show();
    Log.e("TTS", "Language is not supported");
    }
    // Enable the button - It was disabled in main.xml (Go back and
    // Check it)
    else {
    btnSpeak.setEnabled(true);
    }
    // TTS is not initialized properly
    } else {
    Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG)
    .show();
    Log.e("TTS", "Initilization Failed");
    }


    • Create another method speakOut() and add below code, It is used to read out typed text.

    private void speakOut() {
            //Get the text typed
           String text = txtText.getText().toString();
            //If no text is typed, tts will read out 'You haven't typed text'
            //else it reads out the text you typed
           if (text.length() == 0) {
               tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
           } else {
               tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
           }

       }

    • Don't forget to distroy activity after speak function,otherwise it  may be crashed while running.

    public void onDestroy() {
            // Don't forget to shutdown!
            if (tts != null) {
                tts.stop();
                tts.shutdown();
            }
            super.onDestroy();
        }

    • Thats It ! Run project.

    Download full source code: Download




    Monday, August 12, 2013

    Async task simple example

    AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having the mani[ulate thread and/or handlers.

    Here is an example of simple AsyncTask Demo :
    • Create private class PostTask which extends AsyncTask.
    • add unimplemented methods like-doInBackground,onPostExecute,onPreExecute.
    • insert code in doInBackground method.It acts as a thread and it is also independent from UI.
    • It will not affect the UI or it will not freeze your UI.
    • PostTask class code is given below:

     private class PostTask extends AsyncTask<String , Integer, String>{

        @Override
    protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
        String url=params[0];
        // Dummy code
             for (int i = 0; i <= 100; i += 5) {
               try {
                 Thread.sleep(50);
               } catch (InterruptedException e) {
                 e.printStackTrace();
               }
                publishProgress(i);
             }
             return "All Done!";
       
    }

    @Override
    protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    Log.v("*********************","Progressbar dismissed....");
    super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
    // TODO Auto-generated method stub
    Log.v("*********************","Downloading.....................");
    super.onPreExecute();
    }
        }



    • Now just call this class in onCreate method of MainActivity.java like this:

     new PostTask().execute("http://feeds.pcworld.com/pcworld/latestnews");


    • Don't forget to see LogCat for output.

    Download Source code : Link



    Saturday, August 10, 2013

    Alert Dialog Box

    Alert Dialog box is used to confirm further execution from user. For Example if some data needs to delete,then first of all we have to set confirmation dialog and let user choose whether he/she wants to delete data or not.

    There are basically 3 types of dialog box.

    1. One button dialog box - It uses when only one option available or we can also print some message on it.
    2. Two button dialog box - As above discussion, If user needs to choose one option. like yes/no, OK/cancel etc.
    3. Three button dialog box - It uses positive,negative and neutral button.For Example Save file dialog box-it has three buttons - YES, NO, CANCEL.

    Lets see the code for these dialog box.

    1. ONE Button dialog box.

    First of all  create on project and put below code where you want to show dialog box.

    CODE:


      AlertDialog ad = new AlertDialog.Builder(MainActivity.this).create();
            ad.setTitle("Alert Dialog");
            ad.setMessage("Message Part");
            ad.setIcon(R.drawable.ic_launcher);
           
            ad.setButton("OKEY",
            new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(),
    "You clicked on OKey", Toast.LENGTH_SHORT)
    .show();
    }
    });
           
    ad.show();



    2. TWO Button dialog box.

    CODE:


        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

     


            alertDialog.setTitle("Confirm Delete...");

            alertDialog.setMessage("Are you sure you want delete this?");

            alertDialog.setIcon(R.drawable.delete);
            // Setting Positive "YES" Button

            alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog,int which) {
     

                Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
               }
           });

            // Setting Negative "NO" Button
           alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
           
         Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
               dialog.cancel();
               }
           });
     
           // Showing Alert Message
           alertDialog.show();



    3. THREE Button dialog box.


    CODE:


    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
     
                // Setting Dialog Title
                alertDialog.setTitle("Save File...");

                // Setting Dialog Message
                alertDialog.setMessage("Do you want to save this file?");

                // Setting Icon to Dialog
                alertDialog.setIcon(R.drawable.save);

                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    // User pressed YES button. Write Logic Here
                    Toast.makeText(getApplicationContext(), "You clicked on YES",
                                        Toast.LENGTH_SHORT).show();
                    }
                });

                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    // User pressed No button. Write Logic Here
                    Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                    }
                });

                // Setting Netural "Cancel" Button
                alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    // User pressed Cancel button. Write Logic Here
                    Toast.makeText(getApplicationContext(), "You clicked on Cancel",
                                        Toast.LENGTH_SHORT).show();
                    }
                });

                // Showing Alert Message
                alertDialog.show();

    Download Full Source Code: Download