Pages

Wednesday, December 31, 2014

Android Action Bar Style Generator online

Online Tool

Android Action Bar Style Generator online

Its an amazing tool to lets you customize your action bar with preview and easy to use.

"The Android Action Bar Style Generator allows you to easily create a simple, attractive and seamless custom action bar style for your Android application. It will generate all necessary nine patch assets plus associated XML drawables and styles which you can copy straight into your project. "



Output we can download zip folder.



Open  Android Action Bar Style Generator

Thanks enjoy :)

Saturday, November 8, 2014

Show/Hide Password text in Android (Password type EditText View)


Sometime, we have password field in android appliction. In some special case we want show and hide password. see below simple tutorial demo for that.

1. Create XML file in layout folder "res/layout/activity_hideshowpassword.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" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#99afafaf"
        android:gravity="center"
        android:padding="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:shadowColor="@android:color/black"
            android:shadowDx="0.5"
            android:shadowDy="0.5"
            android:shadowRadius="1"
            android:text="Show/Hide Password"
            android:textColor="@android:color/white"
            android:textSize="22sp"
            android:textStyle="bold" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="20dp"
        android:text="Password"
        tools:context=".MainActivity" />

    <EditText
        android:id="@+id/edt_Password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="14dp"
        android:ems="10"
        android:inputType="textPassword" >

        <requestFocus />
    </EditText>

    <CheckBox
        android:id="@+id/chbox_showpassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="8dp"
        android:text="Show Password" />

</LinearLayout>


2. Create on activity java file "ShowHidePasswordActivity.java"

import android.app.Activity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

public class ShowHidePasswordActivity extends Activity {

 private EditText edt_password;
 private CheckBox mCbShowPwd;

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

  edt_password = (EditText) findViewById(R.id.edt_Password);
  mCbShowPwd = (CheckBox) findViewById(R.id.chbox_showpassword);

  //Add onCheckedListener
  mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (!isChecked) {
     //Show password
     edt_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
    } else {
     //Hide password
     edt_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    }
   }
  });
 }
}




3.Add ShowHidePasswordActivity activity class in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ShowHidePasswordActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 


4. ScreenShot




Download APK file Here
Enjoy :)
Thank you.

Friday, October 31, 2014

Image Cropping in android : While capture image or select from gallery

Hello everyone, I write example code for capture & select image from gallery and cropping image in android. see below example code.

1. Create XML file in layout folder "res/layout/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="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_select_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="Select Image" />

    <ImageView
        android:id="@+id/img_photo"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="10dp"
        android:scaleType="fitXY" />

</LinearLayout>
2. Create XML file in layout folder "res/layout/croping_selector.xml".


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text=""
        android:textColor="@android:color/black"
        android:textSize="16sp" />

</LinearLayout>

3. Create an activity Java file "MainActivity.java".


package com.limbani.imagecropping;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private final static int REQUEST_PERMISSION_REQ_CODE = 34;
        private static final int CAMERA_CODE = 101, GALLERY_CODE = 201, CROPING_CODE = 301;

        private Button btn_select_image;
        private ImageView imageView;
        private Uri mImageCaptureUri;
        private File outPutFile = null;

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

            outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

            btn_select_image = (Button) findViewById(R.id.btn_select_image);
            imageView = (ImageView) findViewById(R.id.img_photo);

            btn_select_image.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    selectImageOption();
                }
            });
        }

        private void selectImageOption() {
            final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Add Photo!");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {

                    if (items[item].equals("Capture Photo")) {

                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
                        mImageCaptureUri = Uri.fromFile(f);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                        startActivityForResult(intent, CAMERA_CODE);

                    } else if (items[item].equals("Choose from Gallery")) {

                        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, GALLERY_CODE);

                    } else if (items[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }

    @Override
    protected void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(final int requestCode, final @NonNull String[] permissions, final @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_REQ_CODE: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && null != data) {

                mImageCaptureUri = data.getData();
                System.out.println("Gallery Image URI : "+mImageCaptureUri);
                CropingIMG();

            } else if (requestCode == CAMERA_CODE && resultCode == Activity.RESULT_OK) {

                System.out.println("Camera Image URI : "+mImageCaptureUri);
                CropingIMG();
            } else if (requestCode == CROPING_CODE) {

                try {
                    if(outPutFile.exists()){
                        Bitmap photo = decodeFile(outPutFile);
                        imageView.setImageBitmap(photo);
                    }
                    else {
                        Toast.makeText(getApplicationContext(), "Error while save image", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        private void CropingIMG() {

            final ArrayList<cropingoption> cropOptions = new ArrayList<cropingoption>();

            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setType("image/*");

            List<resolveinfo> list = getPackageManager().queryIntentActivities( intent, 0 );
            int size = list.size();
            if (size == 0) {
                Toast.makeText(this, "Cann't find image croping app", Toast.LENGTH_SHORT).show();
                return;
            } else {
                intent.setData(mImageCaptureUri);
                intent.putExtra("outputX", 512);
                intent.putExtra("outputY", 512);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("scale", true);

                //TODO: don't use return-data tag because it's not return large image data and crash not given any message
                //intent.putExtra("return-data", true);

                //Create output file here
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));

                if (size == 1) {
                    Intent i   = new Intent(intent);
                    ResolveInfo res = (ResolveInfo) list.get(0);

                    i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                    startActivityForResult(i, CROPING_CODE);
                } else {
                    for (ResolveInfo res : list) {
                        final CropingOption co = new CropingOption();

                        co.title  = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                        co.icon  = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                        co.appIntent= new Intent(intent);
                        co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                        cropOptions.add(co);
                    }

                    CropingOptionAdapter adapter = new CropingOptionAdapter(getApplicationContext(), cropOptions);

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Choose Croping App");
                    builder.setCancelable(false);
                    builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                        public void onClick( DialogInterface dialog, int item ) {
                            startActivityForResult( cropOptions.get(item).appIntent, CROPING_CODE);
                        }
                    });

                    builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel( DialogInterface dialog ) {

                            if (mImageCaptureUri != null ) {
                                getContentResolver().delete(mImageCaptureUri, null, null );
                                mImageCaptureUri = null;
                            }
                        }
                    } );

                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        }

        private Bitmap decodeFile(File f) {
            try {
                // decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);

                // Find the correct scale value. It should be the power of 2.
                final int REQUIRED_SIZE = 512;
                int width_tmp = o.outWidth, height_tmp = o.outHeight;
                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                        break;
                    width_tmp /= 2;
                    height_tmp /= 2;
                    scale *= 2;
                }

                // decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            } catch (FileNotFoundException e) {
            }
            return null;
        }
    }


4. Create Java file "CropingOption.java"


package com.limbani.imagecropping;

import android.content.Intent;
import android.graphics.drawable.Drawable;

public class CropingOption {
    public CharSequence title;
    public Drawable icon;
    public Intent appIntent;
}

5. Create Java file "CropingOptionAdapter.java"


package com.limbani.imagecropping;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CropingOptionAdapter extends ArrayAdapter {
    private ArrayList mOptions;
    private LayoutInflater mInflater;

    public CropingOptionAdapter(Context context, ArrayList options) {
        super(context, R.layout.croping_selector, options);

        mOptions  = options;

        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup group) {
        if (convertView == null)
            convertView = mInflater.inflate(R.layout.croping_selector, null);

        CropingOption item = (CropingOption) mOptions.get(position);

        if (item != null) {
            ((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
            ((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);

            return convertView;
        }

        return null;
    }
}

6. Add your activity class and user permission in "AndroidManifest.xml".


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.imagecropping">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


7. ScreenShot".







Thanks :)
Download Code

Saturday, October 18, 2014

Sending SMS in Android

There are two way to send SMS in Android


1. Using Intent to send SMS
2. Using SmsManager to send SMS

* Using Intent to send SMS

 We can use Intent to send SMS by calling default SMS functionality of the Android. It's easy to use because we don’t have to do anything special.

1. Create XML file in layout folder "res/layout/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" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="15dp" >

        <Button
            android:id="@+id/btnComposeSMS"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Open Compose SMS" />
    </LinearLayout>

</LinearLayout>


 2. Create on activity java file "MainActivity.java"

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


 private Button btnOpenComposeSMS;


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

  btnOpenComposeSMS = (Button) findViewById(R.id.btnComposeSMS);

  //Open Compose SMS Button Client Event Code here 
  btnOpenComposeSMS.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {

    Intent smsIntent = new Intent(Intent.ACTION_VIEW);
    smsIntent.setData(Uri.parse("smsto:"));
    smsIntent.setType("vnd.android-dir/mms-sms");

    smsIntent.putExtra("address"  , new String ("0000000000"));
    smsIntent.putExtra("sms_body"  , "Open Comopse SMS using Intent");
    try {
     startActivity(smsIntent);
    } catch (android.content.ActivityNotFoundException ex) {
     Toast.makeText(MainActivity.this,"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
    }
   }
  });

 }
}


3.Add your activity class in AndroidMenifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.sendsms"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest> 


4. Screenshot




*Using SmsManager to send SMS

In Android provide SmsManager API to send SMS programmatically. see below example code.

1. Create XML file in layout folder "res/layout/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" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="15dp" >

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

        <EditText
            android:id="@+id/edt_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:ems="10"
            android:inputType="phone" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Message" />

        <EditText
            android:id="@+id/edt_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:gravity="top"
            android:minLines="5"
            android:text="Send SMS Demo Application" />

        <Button
            android:id="@+id/btnSend"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Send" />
    </LinearLayout>

</LinearLayout>

2. Create on activity java file "MainActivity.java"

package com.limbani.sendsms;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


 private Button btnSend;
 private EditText edtNumber, edtMessage;


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

  btnSend = (Button) findViewById(R.id.btnSend);

  edtNumber = (EditText) findViewById(R.id.edt_number);
  edtMessage = (EditText) findViewById(R.id.edt_message);

  //Send Button Client Event Code here
  btnSend.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    String number = edtNumber.getText().toString().trim();
    String message = edtMessage.getText().toString().trim();

    if(number.length() <= 0){
     Toast.makeText(MainActivity.this,"Please enter Number", Toast.LENGTH_SHORT).show();
    }
    else if (message.length() <= 0) {
     Toast.makeText(MainActivity.this,"Please enter message", Toast.LENGTH_SHORT).show();
    }
    else {
     try {
      SmsManager smsManager = SmsManager.getDefault();
      smsManager.sendTextMessage(number, null, message, null, null);
      Toast.makeText(getApplicationContext(), "SMS successfully sent",  Toast.LENGTH_LONG).show();
     } catch (Exception e) {
      Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
      e.printStackTrace();
     }
    }
   }
  });

 }
}



3.  Add your activity class in AndroidManifest.xml file.
Add user pemission
"
 <uses-permission android:name="android.permission.SEND_SMS"/>
"



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.sendsms"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



4. Screenshot


Download APK file Here

Tuesday, October 14, 2014

ViewTreeObserver - How to get layout width and height run time in android?

Example code for how to use ViewTreeObserver to get run time get layout height and width in Androd.

You can add a tree observer to the layout. This should return the correct width and height. onCreate is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width. Put this on the onCreate method

LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight();
  //TODO: code
  System.out.println("Layout Height : "+height+ "and Layuot Width : "+width);
    } 
});


Thank you :)

Wednesday, May 7, 2014

Custom Radio Buttons example in android

In this Post, Custom Radio Buttons using Drawable Resource(color code in selector XML files).



I have create two XML file. one for Radio Buttons Background selector and second for Radio Buttons text color selector.

1. Create One XML file in "res/drawable/rbtn_selector.xml" add below XML code for Radio Button background.

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

    <item android:state_checked="true"><shape>
            <solid android:color="#1c5fab" />

            <stroke android:width="1dp" android:color="#1c5fab" />
        </shape></item>
    <item android:state_checked="false"><shape android:shape="rectangle">
            <solid android:color="#ffffff" />

            <stroke android:width="1dp" android:color="#1c5fab" />
        </shape></item>

</selector>
Note : If we have custom background PNG images for radio Button background then create Selector like below(Put your images in "res/drawable" folder).

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

    <item android:drawable="@drawable/bg_radio_button_checked" android:state_checked="true"/>
    <item android:drawable="@drawable/bg_radio_button_unchecked" android:state_checked="false"/>

</selector>

2. Create One XML file in "res/drawable/rbtn_textcolor_selector.xml" add below XML code for Radio Buttons Text selector color.(Text Color Selector xml file)

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

    <item android:state_checked="true" android:color="#ffffffff"/>
    <item android:color="#ff1c5fab"/>

</selector>
3. create XML file in layout folder "res/layout/activity_customradiobutton.xml".

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="10dp" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radioAndroid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rbtn_selector"
            android:button="@null"
            android:checked="true"
            android:gravity="center"
            android:padding="5dp"
            android:text="Android"
            android:textColor="@drawable/rbtn_textcolor_selector" />

        <RadioButton
            android:id="@+id/radioiPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rbtn_selector"
            android:button="@null"
            android:gravity="center"
            android:padding="5dp"
            android:text="iPhone"
            android:textColor="@drawable/rbtn_textcolor_selector" />

        <RadioButton
            android:id="@+id/radioWindows"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rbtn_selector"
            android:button="@null"
            android:gravity="center"
            android:padding="5dp"
            android:text="Windows"
            android:textColor="@drawable/rbtn_textcolor_selector" />
    </RadioGroup>

</LinearLayout>
4. Create on activity java file "CustomRadioButtonActivity.java"
I have use setOnCheckedChangeListener for  a callback to be invoked when the checked radio button changed in this group.

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;


public class CustomRadioButtonActivity extends Activity
{

 private RadioGroup radioGroup1;

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

  radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);

  // Checked change Listener for RadioGroup 1
  radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() 
  {
   @Override
   public void onCheckedChanged(RadioGroup group, int checkedId) 
   {
    switch (checkedId) 
    {
    case R.id.radioAndroid:
     Toast.makeText(getApplicationContext(), "Android RadioButton checked", Toast.LENGTH_SHORT).show();
     break;
    case R.id.radioiPhone:
     Toast.makeText(getApplicationContext(), "iPhone RadioButton checked", Toast.LENGTH_SHORT).show();
     break;
    case R.id.radioWindows:
     Toast.makeText(getApplicationContext(), "windows RadioButton checked", Toast.LENGTH_SHORT).show();
     break;
    default:
     break;
    }
   }
  });
 }
}

5. Add your activity class in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.masterapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.limbani.masterapp.CustomRadioButtonActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
Doanload Sample Here

enjoy :)
Thank you.

Radio Buttons example in Android

In this post, I write sample code for RadioButtons with RadioGroup.
Generally RadioButtons are grouped with RadioGroup, If RadioButtons are in group, when one RadioButton within a group is selected, all others are automatically deselected.

Also we can set orientation of the RadioButton vertical or horizontal using below property of the RadioGroup. I show RadioButtons both orientation in XML layout I have create two RadioButton there for example.

        android:orientation="horizontal"
        or
        android:orientation="vertical"

1. create xml file in layout folder "activity_radiobutton.xml".

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="10dp" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radioAndroid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Android" />

        <RadioButton
            android:id="@+id/radioiPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="iPhone" />

        <RadioButton
            android:id="@+id/radioWindows"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Windows" />
    </RadioGroup>

    <RadioGroup
        android:id="@+id/radioGroup2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:orientation="vertical" >

        <RadioButton
            android:id="@+id/radioAndroid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Android" />

        <RadioButton
            android:id="@+id/radioiPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="iPhone" />

        <RadioButton
            android:id="@+id/radioWindows"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Windows" />
    </RadioGroup>

    <Button
        android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="Display" />

</LinearLayout>

2. Create on activity java file "RadioButtonActivity.java"
I have use setOnCheckedChangeListener for  a callback to be invoked when the checked radio button changed in this group.

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.limbani.masterapp.R;

public class RadioButtonActivity extends Activity
{

 private RadioGroup radioGroup1 , radioGroup2;
 private Button btnDisplay;

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

  btnDisplay = (Button) findViewById(R.id.btnDisplay);

  radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
  radioGroup2 = (RadioGroup) findViewById(R.id.radioGroup2);

  // Checked change Listener for RadioGroup 1
  radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() 
  {
   @Override
   public void onCheckedChanged(RadioGroup group, int checkedId) 
   {
    switch (checkedId) 
    {
    case R.id.radioAndroid:
     Toast.makeText(getApplicationContext(), "Android", Toast.LENGTH_SHORT).show();
     break;
    case R.id.radioiPhone:
     Toast.makeText(getApplicationContext(), "iPhone", Toast.LENGTH_SHORT).show();
     break;
    case R.id.radioWindows:
     Toast.makeText(getApplicationContext(), "windows", Toast.LENGTH_SHORT).show();
     break;
    default:
     break;
    }
   }
  });

  // Checked change Listener for RadioGroup 2 
  radioGroup2.setOnCheckedChangeListener(new OnCheckedChangeListener() 
  {
   @Override
   public void onCheckedChanged(RadioGroup group, int checkedId) 
   {
    switch (checkedId) 
    {
    case R.id.radioAndroid:
     Toast.makeText(getApplicationContext(), "Android", Toast.LENGTH_SHORT).show();
     break;
    case R.id.radioiPhone:
     Toast.makeText(getApplicationContext(), "iPhone", Toast.LENGTH_SHORT).show();
     break;
    case R.id.radioWindows:
     Toast.makeText(getApplicationContext(), "windows", Toast.LENGTH_SHORT).show();
     break;
    default:
     break;
    }
   }
  });


  //here displa checked radio button from radio group 1 only also we check same like radio gruop 2
  btnDisplay.setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    int selectedId = radioGroup1.getCheckedRadioButtonId();

    // find the radiobutton by returned id
    RadioButton radioButton = (RadioButton) findViewById(selectedId);
    Toast.makeText(RadioButtonActivity.this, radioButton.getText(), Toast.LENGTH_SHORT).show();
   }
  });
 }
}


3. Add your activity class in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.masterapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.limbani.masterapp.RadioButtonActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

4. Screen Shot



Download APK file Here

enjoy :)
Thank you.

Monday, April 21, 2014

How to get MNC(mobile network code) and MCC(Mobile country code) in android?

Hello Friends, In this post M writing code for getting Mobile network code(MNC) and Mobile country code(MCC) in android. I using TelephonyManager class to getting MNC and MCC. No need any permission for getting this.

A mobile network code (MNC) is used in combination with a mobile country code (MCC) (also known as a "MCC / MNC tuple") to uniquely identify a mobile phone operator/carrier using the GSM/LTE, CDMA, iDEN, TETRA and UMTS public land mobile networks and some satellite mobile networks. SeeHere


1. MainActivity.java class

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class MainActivity extends Activity 
{

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

  TextView txta = (TextView) findViewById(R.id.textView1);
  
  TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
     String networkOperator = tel.getNetworkOperator();
     int mcc = 0, mnc = 0;
     if (networkOperator != null) {
         mcc = Integer.parseInt(networkOperator.substring(0, 3));
         mnc = Integer.parseInt(networkOperator.substring(3));
     }
     txta.setText("MCC : "+mcc+"\n"
       + "MNC : "+mnc);
 }
}


2. activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp" >

    <TextView
         android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example code for getting Mobile network code(MNC) and mobile country code (MCC)"
        android:textSize="14sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="" />

</LinearLayout>


3. ScreenShot



Download APK file Here
enjoy :)
Thank you. 

Tuesday, April 15, 2014

How to get screen height, width and density of the android device?


Hello Friends, in this post, I write code for getting Screen Density and Screen DensityDPI, width and height of the android device using DisplayMetrics

DisplayMetrics
A structure describing general information about a display, such as its size, density, and font scaling.
To access the DisplayMetrics members, initialize an object like this:

 DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);

density
The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

This value does not exactly follow the real screen size (as given by xdpi and ydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240x320 screen will have a density of 1 even if its width is 1.8", 1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be increased (probably to 1.5).

densityDpi
The screen density expressed as dots-per-inch. May be either DENSITY_LOW, DENSITY_MEDIUM, or DENSITY_HIGH.

scaledDensity
A scaling factor for fonts displayed on the display. This is the same as density, except that it may be adjusted in smaller increments at runtime based on a user preference for the font size.

heightPixels
The absolute height of the display in pixels.

widthPixels
The absolute width of the display in pixels.


1. MainActivity.java Class

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;

public class MainActivity extends Activity 
{
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  TextView txta = (TextView) findViewById(R.id.textView);

  DisplayMetrics metrics = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(metrics);
  float screenDensity = metrics.density;
  int screenDensityDPI = metrics.densityDpi;
  float screenscaledDensity = metrics.scaledDensity;
  int width = metrics.widthPixels;
  int Height = metrics.heightPixels;

  txta.setText("Screen Density=" + screenDensity + "\n"
    + "Screen DensityDPI=" + screenDensityDPI + "\n"
    + "Screen Scaled DensityDPI=" + screenscaledDensity + "\n"
    + "Height="+ Height + "\n"
    + "Width=" + width);
 }
}


2. activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="14sp"
        android:textStyle="bold" />

</LinearLayout>


3. Screenshot(HTC Desire X)





Thursday, April 10, 2014

Contains method in an ArrayList with custom class in android?

In this post, If we use Custom class in ArrayList<> and if want to check item already in ArrayList<> or not using Contain method.

Contain Method generally match all variable of the class See.

Now I write a code for check specific variable value already contain in ArrayList<> or not.
Just we need @Override equale() and hashcode() Method in our custom class. like below.

I have created one custom class name is student. While we call contains Method then check only Student first Name. if we want to check multiple variable then we can add like below in @Override equale() and hashcode() Method.

1. Student.java

public class Student 
{
 private int s_rollNo = 0;
 private String s_fname = "";
 private String s_lname = "";
 private String s_contactNumber = "";
 
 public Student(int rollNo, String firstName, String lastName, String contactNo) 
 {
  this.setS_rollNo(rollNo);
  this.setS_fname(firstName);
  this.setS_lname(lastName);
  this.setS_contactNumber(contactNo);
 }
 
 public Student() 
 { 
 }

 public int getS_rollNo() {
  return s_rollNo;
 }
 public void setS_rollNo(int s_rollNo) {
  this.s_rollNo = s_rollNo;
 }
 public String getS_fname() {
  return s_fname;
 }
 public void setS_fname(String s_fname) {
  this.s_fname = s_fname;
 }
 public String getS_lname() {
  return s_lname;
 }
 public void setS_lname(String s_lname) {
  this.s_lname = s_lname;
 }
 public String getS_contactNumber() {
  return s_contactNumber;
 }
 public void setS_contactNumber(String s_contactNumber) {
  this.s_contactNumber = s_contactNumber;
 }
 
 /*
 * Here Equals method code perform when we try use contain method and the check only Student first name
 * Also we can check multiple variables like below
 */
 @Override
 public boolean equals(Object object) 
 {
  boolean sameSame = false;

  if (object != null && object instanceof Student)
  {
   //for match only student rollno
   //sameSame = this.s_rollNo == ((Student) object).s_rollNo;
   
   //for match only student first name
   sameSame = this.s_fname == ((Student) object).s_fname;
   
   // also we can match both paramater here. if required 
  }

  return sameSame;
 }
 
 @Override
 public int hashCode() 
 {
  int result = 17;
  
  //hash code for checking rollno
  //result = 31 * result + (this.s_rollNo == 0 ? 0 : this.s_rollNo);
  
  //hash code for checking fname
  result = 31 * result + (this.s_fname == null ? 0 : this.s_fname.hashCode());
  
  return result;
 }
}


2. Activity class is MainActivity.java  and I have some dummy data for testing

import java.util.ArrayList;

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

public class MainActivity extends Activity 
{
 ArrayList arrStudents = new ArrayList();

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

  TextView txt = (TextView) findViewById(R.id.textView1);
 
  // here add some data in ArrayList herer
  arrStudents.add(new Student(1,"Ajay","asdasd","3215461321"));
  arrStudents.add(new Student(2,"Rahul","ghdtd","1231231231"));
  arrStudents.add(new Student(3,"Jigar","fg","9998468465"));
  arrStudents.add(new Student(4,"Megha","ldZ","1212712545"));
  arrStudents.add(new Student(5,"Ravi","eyr","1224575131"));
  arrStudents.add(new Student(6,"Rajesh","asd","3416461213"));

  // create new student for check in Arraylist Student first Name contain or not
  Student std = new Student(8,"Rajesh","adfgdfg","123123123");
  //Student std = new Student(4123,"Rajesh","123123","123123123");

  if(arrStudents.contains(std))
  {
   txt.setText(std.toString() +"\n\nNew student First Name already contain in ArrayList index no: "+arrStudents.indexOf(std));
  }
  else 
  {
   arrStudents.contains(std);
   txt.setText(std.toString() +"\n\nNew student successfully add");
  }
 }
}


3. activity_main.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example code for check Student First name in arraylist Using contains method"
        android:textSize="14sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="SampleText" />

</LinearLayout>


4. ScreenShot




This code working Perfectly. Enjoy :) Thank you..


Other Post

- Sorting ArrayList (String ArrayList and custom class)


Wednesday, April 9, 2014

DatePickerDialog in android DialogFragment?

This post I write code for display DatePickerDialog using FragmentDialog.

Generally we display DatePickerDialog using  "onCreateDialog (int id)" Method like below.

//.....
static final int DATE_DIALOG_ID = 999;

//
//

call below code to display DatePickerDialog
showDialog(DATE_DIALOG_ID);

//
//

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
       // set date picker as current date
       return new DatePickerDialog(this, datePickerListener, year, month, day);
    }
   return null;
}
//
//

//we use DatePickerDialog.OnDateSetListener Listner to get selected date like below
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener()
{
    public void onDateSet(DatePicker view, int selectedYear,  int selectedMonth, int selectedDay) {
    }
};




But now "Dialog onCreateDialog(int id)" method deprecated in API level 8. 
So now we can use DialogFragment to display DatePickerDialog and this code working to all android version. I finding DatePickerDialogFragmetn.java class from here.


1. Copy DatePickerDialogFragment.java in your application package.

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.widget.DatePicker;


public class DatePickerDialogFragment extends DialogFragment 
{    
    public static final String YEAR = "Year";
    public static final String MONTH = "Month";
    public static final String DATE = "Day";
    
    private OnDateSetListener mListener;
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mListener = (OnDateSetListener) activity;
    }
    
    @Override
    public void onDetach() {
        this.mListener = null;
        super.onDetach();
    }
    
    @TargetApi(11)
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) 
    {
        Bundle b = getArguments();
        int y = b.getInt(YEAR);
        int m = b.getInt(MONTH);
        int d = b.getInt(DATE);
            
        final DatePickerDialog picker = new DatePickerDialog(getActivity(), getConstructorListener(), y, m, d);
        
        if (hasJellyBeanAndAbove()) {
            picker.setButton(DialogInterface.BUTTON_POSITIVE, 
                    getActivity().getString(android.R.string.ok),
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DatePicker dp = picker.getDatePicker();
                    mListener.onDateSet(dp, 
                            dp.getYear(), dp.getMonth(), dp.getDayOfMonth());
                }
            });
            picker.setButton(DialogInterface.BUTTON_NEGATIVE,
                    getActivity().getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {}
            });
        }
        return picker;
    }
    
    private static boolean hasJellyBeanAndAbove() 
    {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }
    
    private OnDateSetListener getConstructorListener() {
        return hasJellyBeanAndAbove() ? null : mListener;
    }
}


2. Create MainActivity.java

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity implements OnDateSetListener
{
 private TextView tvDisplayDate;
 private Button btnChangeDate;

 private int year;
 private int month;
 private int day;

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

  setCurrentDate();
  button_clickEvent();
 }

 // display current date
 public void setCurrentDate() 
 {
  tvDisplayDate = (TextView) findViewById(R.id.tvDate);
  
  final Calendar c = Calendar.getInstance();
  year = c.get(Calendar.YEAR);
  month = c.get(Calendar.MONTH);
  day = c.get(Calendar.DAY_OF_MONTH);

  Format formatter = new SimpleDateFormat("dd-MM-yyyy");
  String s = formatter.format(c.getTime());
  
  tvDisplayDate.setText(s);  
 }

 public void button_clickEvent() 
 {
  btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
  btnChangeDate.setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    Bundle b = new Bundle();
    b.putInt(DatePickerDialogFragment.YEAR, year);
    b.putInt(DatePickerDialogFragment.MONTH, month);
    b.putInt(DatePickerDialogFragment.DATE, day);
    DialogFragment picker = new DatePickerDialogFragment();
    picker.setArguments(b);
    picker.show(getFragmentManager(), "fragment_date_picker");
   }
  });
 }
 
 @Override
 public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) 
 {
  this.year = year;
  this.month = monthOfYear;
  this.day = dayOfMonth;
  
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.YEAR, year);
  calendar.set(Calendar.MONTH, monthOfYear);
  calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
  
  Format formatter = new SimpleDateFormat("dd-MM-yyyy");
  String s = formatter.format(calendar.getTime());
  
  tvDisplayDate.setText(s);
 }
}


3. 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:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Current Date (dd-MM-yyyy): "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="asdasd"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Change Date" />

</LinearLayout>


4. ScreenShot





Download APK file Here

Reference link for new version DatePickerDialog issues.

- Jelly Bean DatePickerDialog — is there a way to cancel?
- android-android-4-1-emulator-invoking-ondateset-twice-from-datepicker-dialog



Tuesday, March 25, 2014

How to enable/disable buttons of the AlertDialog in Android?

Hello friends,
Today m posting to how enable/disable AlertDialog positive and negative Buttons.


AlertDialog.Builder builder = new AlertDialog.Builder(AddSchedule.this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("Alert dialog title");
builder.setMessage("Dialog message");
builder.setPositiveButton("Button1", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) {
        //DO TASK
    }
});
builder.setNegativeButton("Button2", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) {
        //DO TASK
    }
});

AlertDialog dialog = builder.create();
dialog.show();

//After calling show method, you need to check your condition and 
//enable/ disable buttons of dialog 
if(your_condition_true)
    dialog.getButton(AlertDialog.BUTTON1).setEnabled(false); //BUTTON1 is positive button

For nagative button

dialog.getButton(AlertDialog.BUTTON2).setEnabled(false); //BUTTON2 is negative button

And the setOnShowListener since level 8 API (FroYo), does the same,


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new OnShowListener() 
{
    @Override
    public void onShow(DialogInterface dialog) 
 {
        if(condition)
        ((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }
});
dialog.show();


Thursday, March 13, 2014

How to get absolute path when select image from gallery and SD Card (Kitkat and lower android version)?

In some special cast to need get image from gallery to display in application. so I am posting to get absolute path of the selected image from gallery using Intent.ACTION_GET_CONTENT.

In Kitkat version we get different Uri format(DocumentProvider)
Now
Uri format like this : content://com.android.providers.media.documents/document/image:3951
Before
Uri format like this : content://media/external/images/media/3951.

See the Kikat version change here

1. AbsolutePathActivity.java Activity Class

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
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 AbsolutePathActivity extends Activity 
{
 private static final int MY_INTENT_CLICK=302;
 private TextView txta;
 private Button btn_selectImage;

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

  txta = (TextView) findViewById(R.id.textView1);
  btn_selectImage = (Button) findViewById(R.id.btn_selectImage);

  btn_selectImage.setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    Intent intent = new Intent(); 
    intent.setType("*/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent, "Select File"),MY_INTENT_CLICK);
   }
  });

 }

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data)
 {
  if (resultCode == RESULT_OK)
  {
   if (requestCode == MY_INTENT_CLICK)
   {
    if (null == data) return;

    String selectedImagePath;
    Uri selectedImageUri = data.getData();

    //MEDIA GALLERY
    selectedImagePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
    Log.i("Image File Path", ""+selectedImagePath);
    txta.setText("File Path : \n"+selectedImagePath);
   }
  }
 }
}

Copy below class on your application for getting Gallery image file Uri AbsolutePath.

2.ImageFilePath.java  

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class ImageFilePath 
{
 
 
 /**
  * Method for return file path of Gallery image 
  * 
  * @param context
  * @param uri
  * @return path of the selected image file from gallery
  */
 public static String getPath(final Context context, final Uri uri) 
 {

  //check here to KITKAT or new version
  final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

  // DocumentProvider
  if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
   
   // ExternalStorageProvider
   if (isExternalStorageDocument(uri)) {
    final String docId = DocumentsContract.getDocumentId(uri);
    final String[] split = docId.split(":");
    final String type = split[0];

    if ("primary".equalsIgnoreCase(type)) {
     return Environment.getExternalStorageDirectory() + "/" + split[1];
    }
   }
   // DownloadsProvider
   else if (isDownloadsDocument(uri)) {

    final String id = DocumentsContract.getDocumentId(uri);
    final Uri contentUri = ContentUris.withAppendedId(
      Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

    return getDataColumn(context, contentUri, null, null);
   }
   // MediaProvider
   else if (isMediaDocument(uri)) {
    final String docId = DocumentsContract.getDocumentId(uri);
    final String[] split = docId.split(":");
    final String type = split[0];

    Uri contentUri = null;
    if ("image".equals(type)) {
     contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else if ("video".equals(type)) {
     contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    } else if ("audio".equals(type)) {
     contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    }

    final String selection = "_id=?";
    final String[] selectionArgs = new String[] {
      split[1]
    };

    return getDataColumn(context, contentUri, selection, selectionArgs);
   }
  }
  // MediaStore (and general)
  else if ("content".equalsIgnoreCase(uri.getScheme())) {

   // Return the remote address
   if (isGooglePhotosUri(uri))
    return uri.getLastPathSegment();

   return getDataColumn(context, uri, null, null);
  }
  // File
  else if ("file".equalsIgnoreCase(uri.getScheme())) {
   return uri.getPath();
  }

  return null;
 }

 /**
  * Get the value of the data column for this Uri. This is useful for
  * MediaStore Uris, and other file-based ContentProviders.
  *
  * @param context The context.
  * @param uri The Uri to query.
  * @param selection (Optional) Filter used in the query.
  * @param selectionArgs (Optional) Selection arguments used in the query.
  * @return The value of the _data column, which is typically a file path.
  */
 public static String getDataColumn(Context context, Uri uri, String selection,
   String[] selectionArgs) {

  Cursor cursor = null;
  final String column = "_data";
  final String[] projection = {
    column
  };

  try {
   cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
     null);
   if (cursor != null && cursor.moveToFirst()) {
    final int index = cursor.getColumnIndexOrThrow(column);
    return cursor.getString(index);
   }
  } finally {
   if (cursor != null)
    cursor.close();
  }
  return null;
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is ExternalStorageProvider.
  */
 public static boolean isExternalStorageDocument(Uri uri) {
  return "com.android.externalstorage.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is DownloadsProvider.
  */
 public static boolean isDownloadsDocument(Uri uri) {
  return "com.android.providers.downloads.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is MediaProvider.
  */
 public static boolean isMediaDocument(Uri uri) {
  return "com.android.providers.media.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is Google Photos.
  */
 public static boolean isGooglePhotosUri(Uri uri) {
  return "com.google.android.apps.photos.content".equals(uri.getAuthority());
 }
}


3. activity_absolutepath.xml layout file

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example code for get absolute path when select image from gallery"
        android:textSize="14sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_selectImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:text="Select Image" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="14sp"
        android:textStyle="bold" />

</LinearLayout>

4. AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.masterapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.limbani.masterapp.AbsolutePathActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

5. ScreenShot




And Gallery image file Absolute path write in Log as per above code.

That's it, And it's working in Kitkat and  lower version too.

Doanload APK file Here

enjoy :)
Thank you.


Thursday, January 2, 2014

How to make a Skype Audio/Video call and Chat through intent in Android


Hello every one! Today I posting to Skype calls and message from our application. Just we need to open explicit default installed Skype application through Intent.


1. Focus Skype (Open Skype Application)
    
    Uri skypeUri = Uri.parse("skype:");
    Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
    myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
    myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(myIntent);

2. Skype Chat

     Uri skypeUri = Uri.parse("skype:username?chat");
     Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
     myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
     myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(myIntent);

3. Skype Conference Chat with Topic

     Uri skypeUri = Uri.parse("skype:username1;username2?chat&topic=Android%20Chat");
     Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
     myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
     myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(myIntent);

4. Make a Skype call

     Uri skypeUri = Uri.parse("skype:username?call");
     Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
     myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
     myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(myIntent);

5. Make a Skype Video call

     Uri skypeUri = Uri.parse("skype:username?call&video=true");
     Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
     myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
     myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(myIntent); 
 
Example code here.

MainActivity.java Class file


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity 
{
 // Make sure you are sign in skype application if you not then you need to sign in 
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // Open skype button click event code here
  ((Button) findViewById(R.id.openskype)).setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    String mySkypeUri = "skype:";
    SkypeUri(MainActivity.this, mySkypeUri);
   }
  });

  // skype message button click event code here
  ((Button) findViewById(R.id.skypemsg)).setOnClickListener(new OnClickListener() 
  { 
   @Override
   public void onClick(View v) 
   {
    String skypeName = ((EditText) findViewById(R.id.edt_skypeusername)).getText().toString().trim();
    if(skypeName.length()<=0)
    {
     Toast.makeText(getApplicationContext(), "Please enter skype username to message", Toast.LENGTH_SHORT).show();
    }
    else 
    {
     String mySkypeUri = "skype:"+skypeName+"?chat";
     SkypeUri(MainActivity.this, mySkypeUri);
    }
   }
  });

  // Skype Audio call button click event code here
  ((Button) findViewById(R.id.skypecall)).setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    String skypeName = ((EditText) findViewById(R.id.edt_skypeusername)).getText().toString().trim();
    if(skypeName.length()<=0)
    {
     Toast.makeText(getApplicationContext(), "Please enter skype username to call", Toast.LENGTH_SHORT).show();
    }
    else {
     String mySkypeUri = "skype:"+skypeName+"?call";
     SkypeUri(MainActivity.this, mySkypeUri);
    }    
   }
  });

  // Skype Video call button click event code here
  ((Button) findViewById(R.id.skypevideocall)).setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    String skypeName = ((EditText) findViewById(R.id.edt_skypeusername)).getText().toString().trim();
    if(skypeName.length()<=0)
    {
     Toast.makeText(getApplicationContext(), "Please enter skype username to video call", Toast.LENGTH_SHORT).show();
    }
    else 
    {
     String mySkypeUri = "skype:"+skypeName+"?call&video=true";
     SkypeUri(MainActivity.this, mySkypeUri);
    }    
   }
  });
 }

 public void SkypeUri(Context myContext, String mySkypeUri) {
  
  // Make sure the Skype for Android client is installed.
  if (!isSkypeClientInstalled(myContext)) {
   goToMarket(myContext);
   return;
  }
  Uri skypeUri = Uri.parse(mySkypeUri);
  Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
  myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
  myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  myContext.startActivity(myIntent);

  return;
 }
 
 /**
  * Determine whether the Skype for Android client is installed on this device.
  */
 public boolean isSkypeClientInstalled(Context myContext) {
  PackageManager myPackageMgr = myContext.getPackageManager();
  try {
   myPackageMgr.getPackageInfo("com.skype.raider", PackageManager.GET_ACTIVITIES);
  }
  catch (PackageManager.NameNotFoundException e) {
   return (false);
  }
  return (true);
 }

 /**
  * Install the Skype client through the market: URI scheme.
  */
 
 public void goToMarket(Context myContext) {
  Uri marketUri = Uri.parse("market://details?id=com.skype.raider");
  Intent myIntent = new Intent(Intent.ACTION_VIEW, marketUri);
  myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  myContext.startActivity(myIntent);
  return;
 }
}


activity_main.xml XML layout file Here

<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"
    android:padding="15dp"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/skype_intent_handler"
        android:textSize="18sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/edt_skypeusername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:ems="10"
        android:hint="Echo Testing skypeID - echo123" >
    </EditText>

    <Button
        android:id="@+id/openskype"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Open Skype" />

    <Button
        android:id="@+id/skypemsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Skype Message" />

    <Button
        android:id="@+id/skypecall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Skype Audio Call" />

    <Button
        android:id="@+id/skypevideocall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Skype Video Call" />

</LinearLayout>


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.skypeintenthandler"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.limbani.skypeintenthandler.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



Note: Make sure you sign in Skype application. If not then open Skype application and sign in.

More information about Skype URIs are documented at: developer.skype.com/skype-uris-program/skype-uri-ref


Download Tutorial APK file ClickHere

Enjoy :)