Leave a comment  →

This is how you can validate a hex input in android code. The regex it makes use of can be used in other languages as well.

Validation steps are :

  • check if the input is not null or zero length
  • check if the input has even numbers as hex numbers are always even
  • match the input with the validating regex.
public boolean validHexInput(String str) {

   if (str == null || str.length() == 0) {
      return false;
   }

   // length should be even number 
   // otherwise its not a valid hex 
   if (str.length() % 2 == 0) {
      String var1 = "(?i)[0-9a-f]+";
      return str.matches(var1);
 }

 return false;
}


Leave a comment  →

Some times we need the inflater outside activities in android . To get access to the inflator we may use the following code snippet. You can use this outside activities – all you need is to provide a Context:

LayoutInflater inflater = LayoutInflater.from(context);

the from function also checks with assert that you actually get an inflater back and throws an error otherwise – which will be much easier to deal with then a null pointer exception somewhere in the code.

An Alternate way is shown below but I recommend to use the above one:

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Then to retrieve your different widgets, you inflate a layout:

View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );

Leave a comment  →

In my app,I wanted to show the number of taps to be made to accomplish a task, for this purpose i used Toast class , I used Toast.makeText to show the text. problem is that I couldn’t change the text or make it hide quickly if new text was to be shown. Android would queue all the makeText requests.

I wanted to have a solution to be able to change the text or be able to cancel the previous toast without waiting for it to finish. While Looking for solution I found this class called Boast by a StackOverFlow user Richard Le Mesurier. The Boast class accomplishes exactly what I needed.

The trick is to keep track of the last Toast that was shown, and to cancel that one.

What Richard Le Mesurier have done is to create a Toast wrapper, that contains a static reference to the last Toast displayed.

When I need to show a new one, I first cancel the static reference, before showing the new one (and saving it in the static).

Here’s full code of the Boast wrapper Richard Le Mesurier made – it mimics enough of the Toast methods for me to use it.

By default the Boast will cancel the previous one, so you don’t build up a queue of Toasts waiting to be displayed.

This should be a direct drop-in replacement for Toast in most use cases. for example

 mBoast.makeText(this,"your text",Duration).show();
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.widget.Toast;

/**
 * {@link Toast} decorator allowing for easy cancellation of notifications. Use
 * this class if you want subsequent Toast notifications to overwrite current
 * ones. </p>
 *
 * By default, a current {@link Boast} notification will be cancelled by a
 * subsequent notification. This default behaviour can be changed by calling
 * certain methods like {@link #show(boolean)}.
 */
public class Boast
{
    /**
     * Keeps track of certain {@link Boast} notifications that may need to be cancelled.
     * This functionality is only offered by some of the methods in this class.
     */
    private volatile static Boast globalBoast = null;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Internal reference to the {@link Toast} object that will be displayed.
     */
    private Toast internalToast;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Private constructor creates a new {@link Boast} from a given
     * {@link Toast}.
     *
     * @throws NullPointerException
     *         if the parameter is <code>null</code>.
     */
    private Boast(Toast toast)
    {
        // null check
        if (toast == null)
        {
            throw new NullPointerException(
                    "Boast.Boast(Toast) requires a non-null parameter.");
        }

        internalToast = toast;
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Make a standard {@link Boast} that just contains a text view.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text,
                                 int duration)
    {
        return new Boast(Toast.makeText(context, text, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the
     * text from a resource.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId, int duration)
            throws Resources.NotFoundException
    {
        return new Boast(Toast.makeText(context, resId, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view. Duration
     * defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text)
    {
        return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the
     * text from a resource. Duration defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId)
            throws Resources.NotFoundException
    {
        return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Show a standard {@link Boast} that just contains a text view.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     */
    public static void showText(Context context, CharSequence text, int duration)
    {
        Boast.makeText(context, text, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the
     * text from a resource.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    public static void showText(Context context, int resId, int duration)
            throws Resources.NotFoundException
    {
        Boast.makeText(context, resId, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view. Duration
     * defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     */
    public static void showText(Context context, CharSequence text)
    {
        Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the
     * text from a resource. Duration defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    public static void showText(Context context, int resId)
            throws Resources.NotFoundException
    {
        Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Close the view if it's showing, or don't show it if it isn't showing yet.
     * You do not normally have to call this. Normally view will disappear on
     * its own after the appropriate duration.
     */
    public void cancel()
    {
        internalToast.cancel();
    }

    /**
     * Show the view for the specified duration. By default, this method cancels
     * any current notification to immediately display the new one. For
     * conventional {@link Toast#show()} queueing behaviour, use method
     * {@link #show(boolean)}.
     *
     * @see #show(boolean)
     */
    public void show()
    {
        show(true);
    }

    /**
     * Show the view for the specified duration. This method can be used to
     * cancel the current notification, or to queue up notifications.
     *
     * @param cancelCurrent
     *        <code>true</code> to cancel any current notification and replace
     *        it with this new one
     *
     * @see #show()
     */
    public void show(boolean cancelCurrent)
    {
        // cancel current
        if (cancelCurrent && (globalBoast != null))
        {
            globalBoast.cancel();
        }

        // save an instance of this current notification
        globalBoast = this;

        internalToast.show();
    }

}

Leave a comment  →

Ever since Near Field Communication was embedded on mobile phones, loads of new ideas and business proposals made people very busy. So does the Android platform with its API’s supporting NFC. Nexus S looks like a state of the art – good starting point if one wants to get past the monotonic Nokia’s piece of the cake. I just want to share with you my experience on reading a MiFare Classic tag using the Nexus S..and the Android platform.

You need to have:

  • A MiFare Classic 1k Tag – ( hopefully you know the keys for its Blocks :=) )
  • Android SDK and IDE
  • NFC enabled Android  (Make sure if the Android version is 2.3.3 or above).

Some Basics about the card:

MiFare classic cards store data in its Sectors. In MiFare classic 1k card there are 16 of them. Each Sector contains 4 blocks. You can store 16 bytes in each block. Making about 1024 bytes of storage space..that explains the 1K part of the card. You can perform common tasks like reading, writing data on these blocks, authentification, navigating the card sectors by incrementing the blocks count. The first sector contains manufacturer’s details and a unique id for the card. This is a read only part.

Each sector on the Mifare card is secured by two 48-bit keys: A and B. The last block in the sector contains these keys, as well as a configuration that defines what each key can do with each block, i.e block 0 could be configured so that
key A could read and write, but if a reader authenticates with key B, the reader would only be able to read that block.

The rest of the memory storage can be read or written using keys A and B. Fresh, empty Mifare cards have all their sectors locked with a pair of default keys FFFFFFFFFFFF or 000000000000.

Default Keys from experiments

About the NFC part of Android

Since ever 2.3.3 Gingerbread – Android exposes an API to read a list of card technologies. To perform operations on a tag, there are three things to be noted.

  1.  The cards store data in a format,
  2.  Reading and Writing data is done using a protocol
  3.  Cards support a technology that defines what they are

hence reading and writing to these cards can be done only when the data is arranged in that format. MiFare 1K cards support the NDEF format. It also supports NFC – protocol on the communication level. Precisely – ISO 14443 – 3A specification in short NFCA and it uses the MiFare technology.

Now we need to let the Android know what kind of cards we would be using in our application. This is often defined in an XML file stored in the resource folder ( I have named the file – filter_nfc.xml and stored it in a folder named xml). This resource file contains for example,

android.nfc.tech.NfcA
 android.nfc.tech.MifareClassic

Here we have declared a tech-list. This list has to be used in the Manifest file. Imagine you would like to start an activity when a tag is touched. The Manifest file is the right place to let the launcher know what activity is to be called when a particular tag is touched.

In the Manifest file, you would have an element – activity. This would declare the name of the activity, a title for it and some metadata. Ideally you would let the system know that you want to start this activity when you touch a MiFare classic card. You can define you own filters for different activities for a variety of tag and protocol combinations.

You would then set the permissions on your Manifest file.

You can also do this in your onCreate method by using an NfcAdapter,

NfcAdapter mAdapter = NfcAdapter.getDefaultAdapter(this);

When a MiFare tag is discovered, the NFC stack would get the details of the tag and deliver it to a new Intent of this same activity. Hence to handle this, we would need an instance of the PendingIntent from the current activity.

PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,
 new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

Then we could set up our filter which defines the data format and technology type.

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);try {
 ndef.addDataType("*/*");
 } catch (MalformedMimeTypeException e) {
 throw new RuntimeException("fail", e);
 }

 mFilters = new IntentFilter[] {
 ndef,
 };// Setup a tech list for all NfcF tags

 mTechLists = new String[][] { new String[] { MifareClassic.class.getName() } };Intent intent = getIntent();

Finally when the pending intent calls the activity again, we like to read the tag. I have put all the steps in the method resolveIntent which would do only the reading part of the tag.

resolveIntent(intent);

Reading the tag

The method looks like

Continue reading


2 Comments  →
   by Dost Muhammad Shah    2 Comments  →

Anyone who has a Raspberry Pi knows how exciting it is to have this little computer in the palm of your hand. Now with the introduction of the latest model, and with it being more powerful and staying at the same old price, there is so much more you can do now. Looking for something […]

http://lifehacker.com/seven-ready-made-raspberry-pi-projects-you-can-install-1691368805


12 Comments  →
   by Dost Muhammad Shah    12 Comments  →

Playing the default notification sound of the device is the most effective way to notify a user. This can be established by getting the Uri of the audio file from RingtoneManager. To play default alarm tone , ringtone or notification sound from an android app, the following code snippet is useful.

Play Notification Tone

try {
 Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
 Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
 r.play();
 } catch (Exception e) {
 e.printStackTrace();
 }

Play Alarm Tone

To play an Alarm-tone change TYPE_NOTIFICATION to TYPE_ALARM.

try {
 Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
 Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
 r.play();
 } catch (Exception e) {
 e.printStackTrace();
 }

Set & Play a Tone from Raw resources folder

To set a file from the raw folder of your app just change the uri to get the desired file from raw resources. If you have included a tone called sownd.mp3 in your raw resources folder, all you have to do is change

 Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

to

  Uri path = Uri.parse("android.resource://"+getPackageName()+"/raw/sound.mp3");

The code should look like this now

try {
  Uri path = Uri.parse("android.resource://"+getPackageName()+"/raw/sound.mp3");
  // The line below will set it as a default ring tone replace
  // RingtoneManager.TYPE_RINGTONE with RingtoneManager.TYPE_NOTIFICATION
  // to set it as a notification tone
  RingtoneManager.setActualDefaultRingtoneUri(
                    getApplicationContext(), RingtoneManager.TYPE_RINGTONE,
                    path);
  Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), path); 
  r.play();
 } 
catch (Exception e) {
 e.printStackTrace(); 
}

1 Comment  →
   by Dost Muhammad Shah    1 Comment  →

Android developers have to write a lot of findViewbyId() codes in their java classes, which is often boring, this can be avoided by either use of  annotation based library (dependency injection frameworks) like Android Annotations, RoboGuice (which the Official document of Android suggests to avoid ) or use Android Layout Finder (an online tool).

Android Layout Finder tool can automate process of writing findViewById() code and thereby we can have JAVA code automated way and can save our valuable time.You just have to paste XML layout code and it gives you JAVA code with findViewById and click listeners.

Give it a try 🙂


3 Comments  →
   by Dost Muhammad Shah    3 Comments  →

There are many third-party libraries for Android but several of them are “must have” libraries that are extremely popular and are often used in almost any Android project. Each has different purposes but all of them make life as a developer much more pleasant. The major libraries are listed below in a few categories.

Standard Pack

This “standard pack” listed below are libraries that are quite popular, widely applicable and should probably be setup within most Android apps:

Name Description
Retrofit A type-safe REST client for Android which intelligently maps an API into a client interface using annotations.
Picasso A powerful image downloading and caching library for Android.
ButterKnife Using Java annotations, makes Android development better by simplifying common tasks.
Parceler Android Parcelable made easy through code generation
IcePick Android Instance State made easy
Crouton Context-sensitive, configurable alert notices much better than toasts
Hugo Easier logging using annotations

Convenience

  • ButterKnife – Using Java annotations, makes Android development better by simplifying common tasks. Downloadand install as a jar. Make sure to setup eclipse integration for this to work.
  • Dagger – A fast dependency injector for Android and Java.
  • Parceler – Android Parcelable made easy through code generation.
  • IcePick – Android Instance State made easy
  • Hugo – Easier logging within your app
  • AndroidAnnotations – Framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what’s really important. By simplifying your code, it facilitates its maintenance
  • RoboGuice – Powerful extensions to Android using dependency injection.
  • Calligraphy – Custom fonts made easy

Extensions

  • Otto – An enhanced Guava-based event bus with emphasis on Android support
  • EventBus – Android optimized event bus that simplifies communication between components.
  • Tape – Tape is a collection of queue-related classes for Android and Java
  • RxJava – Reactive Extensions for the JVM
  • Priority JobQueue – Easier background tasks
  • ACRA – Crash reporting made easy and free. Check the setup instructions and open-source backend.

Networking

  • Picasso – A powerful image downloading and caching library for Android.
  • Ion – Powerful asynchronous networking library. Download as a jar here.
  • Android Async HTTP – Asynchronous networking client for loading remote content such as JSON.
  • Retrofit – A type-safe REST client for Android and Java which intelligently maps an API into a client interface using annotations.

ListView

Easy Navigation

  • PagerSlidingTabStrip – An interactive indicator to navigate between the different pages of a ViewPager.
  • ViewPagerIndicator – Paging indicator widgets compatible with the ViewPager from the Android Support Library and ActionBarSherlock.
  • JazzyViewPager – Pager with more animations
  • ParallaxPager – ViewPager with Parallax scrolling effects
  • SlidingMenu – Library that allows developers to easily create applications with sliding menus like those made popular in the Google+, YouTube, and Facebook apps.
  • MenuDrawer – Library for easy menu drawers
  • Android Satellite Menu – Radial menu which is configurable reminiscent of the “Path” menu style.
  • ArcMenu – Alternate radial menu modeled after the “Path” menu style.
  • AndroidSlidingUpPanel – Sliding Up Panel
  • DraggablePanel – Panels that can be dragged

UI Components

Drawing

Scanning

Persistence

Compatibility

Resources

Check out the following resources for finding libraries:

References