Monday, 10 June 2013

Setting MaxLength of EditText at run time Andriod


Some times we have to set max length of edit text By Code Or
we can use xml  tag as
android:maxLength="5" 

If we want to limit the character input in an EditText , EditText in XML layout gives us android:maxLength to do this. But in java codes you might wonder why there isn't any setMaxLength(int length) function. The reason behind this is that when you want to restrict the EditText to accept certain value, you have to filter them and this would be invoked by setFilters. To make our EditText to have a fixed size we can use the following code.


                  int maxLength = 5;
                  InputFilter[] FilterArray = new InputFilter[1];
                  FilterArray[0] = new InputFilter.LengthFilter(maxLength);

                  nameTxt.setFilters(FilterArray);



Here is one good example I found on stack over flow by

For anyone else wondering how to achieve this, here is my extended EditText class EditTextNumeric.
.setMaxLength(int) - sets maximum number of digits
.setMaxValue(int) - limit maximum integer value
.setMin(int) - limit minimum integer value
.getValue() - get integer value

import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;

public class EditTextNumeric extends EditText {
    protected int max_value = Integer.MAX_VALUE;
    protected int min_value = Integer.MIN_VALUE;

    // constructor
    public EditTextNumeric(Context context) {
        super(context);
        this.setInputType(InputType.TYPE_CLASS_NUMBER);
    }

    // checks whether the limits are set and corrects them if not within limits
    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        if (max_value != Integer.MAX_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) > max_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(max_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        if (min_value != Integer.MIN_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) < min_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(min_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        super.onTextChanged(text, start, before, after);
    }

    // set the max number of digits the user can enter
    public void setMaxLength(int length) {
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(8);
        this.setFilters(FilterArray);
    }

    // set the maximum integer value the user can enter.
    // if exeeded, input value will become equal to the set limit
    public void setMaxValue(int value) {
        max_value = value;
    }
    // set the minimum integer value the user can enter.
    // if entered value is inferior, input value will become equal to the set limit
    public void setMinValue(int value) {
        min_value = value;
    }

    // returns integer value or 0 if errorous value
    public int getValue() {
        try {
            return Integer.parseInt(this.getText().toString());
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}
Example usage:
final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);
All other methods and attributes that apply to EditText, of course work too.



Friday, 7 June 2013

Start Activity or Service on boot Android


Hi  guys,

We have number of situations in our development that we want our service or our app should be run as soon as  Device Start, or after Boot Completed.

After boot completes the Android system broadcasts an intent with the action android.intent.action.BOOT_COMPLETED. And now all we need is an IntentReceiver, called a BroadcastReceiver, to listen and act on it.

So here is simple example where you can run your  Activity or Service as soon as device Start.
first create simple activity as  our favorite activity MainActivity :P

public class MainActivity extends Activity {

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

       }
      

}


and Here its XML

<RelativeLayout 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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="156dp"
        android:text="App Main Page"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>


 And create simple service to show messages as it created and running etc

TestService.java

public class TestService extends Service {
       public TestService() {
       }

       @Override
       public IBinder onBind(Intent intent) {
              // TODO: Return the communication channel to the service.
              throw new UnsupportedOperationException("Not yet implemented");
       }
       @Override
       public void onCreate() {
              // TODO Auto-generated method stub
       Toast.makeText(getApplicationContext(), "Service Created",1).show();
              super.onCreate();
       }
      
      
       @Override
       public void onDestroy() {
              // TODO Auto-generated method stub
              Toast.makeText(getApplicationContext(), "Service Destroy",1).show();
              super.onDestroy();
       }
      
       @Override
       public int onStartCommand(Intent intent, int flags, int startId) {
              // TODO Auto-generated method stub
              Toast.makeText(getApplicationContext(), "Service Working",1).show();
              return super.onStartCommand(intent, flags, startId);
       }
}



Now when the device finishes booting up, our BroadcastReceiver will receive the BOOT_COMPLETED action in the onReceive() method which is where we’ll start our service


public class BootStartUpReciever extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {
              // TODO: This method is called when the BroadcastReceiver is receiving

              // Start Service On Boot Start Up
              Intent service = new Intent(context, TestService.class);
              context.startService(service);
             
              //Start App On Boot Start Up
              Intent App = new Intent(context, MainActivity.class);
              App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              context.startActivity(App);


       }
}


AndroidManifest.xml

Now we have to modify the AndroidManifest.xml file:

1) adding the permission to capture che event of the boot completed:
2) registering the Service:
3) And The receiver needs to be declared in the manifest, e.g. with the following entry:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.bootstart.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>
       
         <service
            android:name="com.example.bootstart.TestService"
            android:enabled="true"
            android:exported="true" >
        </service>

        <receiver
            android:name="com.example.bootstart.BootStartUpReciever"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

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

You can download complete example Here 

 Happy Codddding :)



Toggle Button Android


Toggle Button - UI Tutorials Series 

Hi Guys I decide to make all simple and complex UI control/view Tutorials for newbies :)
So here is our first example.
Toggle Button in Android
This is just the simple example for implementing Toggle Button in android application
Create Simple Layout as
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="55dp"
        android:textOn="On"
        android:textOff="Off" />


</RelativeLayout>

and Here is Our Favorite MainActivity.java :)

public class MainActivity extends Activity {
       private ToggleButton onOffTBtn;

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

              onOffTBtn = (ToggleButton) findViewById(R.id.toggleButton1);

              onOffTBtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           if (onOffTBtn.isChecked()) {
                                  Toast.makeText(MainActivity.this, "On", 1).show();
                           } else {
                                  Toast.makeText(MainActivity.this, "Off", 1).show();
                           }

                     }
              });
       }

}


you can download example from here 
Happy Coddddddding :)