Android CommonUtils

This post is a part of CommonUtils SDK.

As said in the Part 1 of this post, this SDK is developed to help android developers by reducing their development time and efforts that they invest in coding most of the common features of the app. We already have covered 30 methods of this SDK in Part 1. You will see the rest of the methods in this part.

Just to remind you, you can get the code of this SDK from GitHub. You can add your own methods that can reduce developers’ time and efforts. Any improvements, changes and suggestions are welcomed. And, here is the demo apk file that you can install and check in your devices.

31. Convert ArrayList to comma separated string

This method is used to convert ArrayList to comma separated string.

Parameter:

arrList (Pass ArrayList)

Returns:

It returns comma separated string from ArrayList data.

How to use:

String strlist = Common.arrayListToString(arrList);

32. Play background music

This method is used to play background music.
Note: I n raw folder please add sound with this name “background_music”.

Parameters:
mContext (Pass application context)

How to use:

Common.backgroundMusicStart(mContext);

33. Stop background music

This method is used for S top background music.

Note: I n raw folder please add sound with this name “background_music”.

Parameters:

mContext (Pass application context)

How to use:

Common.backgroundMusicStart(mContext);

34. Apply blur effect on image (Bitmap)

This method is used to apply blur effect on bitmap image.

Parameters:

mContext (Pass application context)

bitmap(Pass bitmap)

Returns:

I t returns blurred image in bitmap.

How to use:

Bitmap bmpImg = Common.blurEffectOnBitmap(mContext, bitmap);

35. Apply blur effect on image (Drawable)

This method is used to apply blur effect on drawable image.

blur

 

Parameters:

mContext (Pass application context)
drawable (Pass drawable object)
radius (for blur effect, integer value it must be below 25)

Returns:

It returns blur image in drawable.

How to use:

Drawable drawableObj = Common.blurEffectOnDrawable(Context, bitmap, radius);

36. Convert drawable to bitmap

This method is used to convert drawable to bitmap image.

Parameters:

mContext (Pass application context)

drawableResourceId (drawable Resource id i.e. :R.drawable.ic_launcher)

Returns:

Returns bitmap image.

How to use:

Bitmap bitmap = Common.drawableToBitmap(mContext, drawableId);

37. Convert bitmap to drawable

This method is used to convert bitmap image to drawable.

Parameters:

mContext (Pass application context)

bitmap (Pass bitmap)

Returns:

It returns drawable image.

How to use:

Common.bitmapToDrawable(mContext, bitmap);

38. Set Application Volume

This method gets device volume and set application sound volume same as device volume.

Parameter:

mContext (Pass application context)

Returns:

This method does not return any value.

How to use:

Common.setCurrentDeviceVolume(mContext);

39. Set bitmap to preferences

This method is used to save bitmap image in preferences as string.

Parameters:

bitmap (Pass bitmap)

mContext (Pass application context)

prefName (Pass preferences name)

prefFileName (Pass shared preference file name)

How to use:

Common.setBitmapToPreference(bitmap, mContext, prefName, appName);

40. Get bitmap image form preference

This method is used to get saved Bitmap image from preferences.

Parameters:

mContext (Pass application context)

prefName (Pass preferences name)

prefFileName (Pass shared preference file name)

Returns:

It returns bitmap image.

How to use:

Common.getBitmapFromPreference(mContext, prefName, appName);

41. Get application version code

This method is used to get app current version code.

Parameter:

mContext (Pass application context)

Returns:

It returns version code.

How to use:

int intVersionCode = Common.getApplicationVersionCode(mContext);

42. Set vertical text-view (left & right)

The following code is used to set textView on left or right side on the device screen.

For left side textview:

<c​om.common.utils.VerticalTextViewLeft
a​ndroid:id=​"​@+id/text1"
a​ndroid:layout_width=​"​wrap_content"
a​ndroid:layout_height=​"​wrap_content"
a​ndroid:text=​"​@string/hello_world"
android:textColor=​"​@android:color/black"​/​>

For right side textview:

<c​om.common.utils.VerticalTextViewRight
a​ndroid:id=​"​@+id/text2"
a​ndroid:layout_width=​"​wrap_content"
android:layout_height=​"​wrap_content"
android:text=​"​@string/hello_world"​/​>

Above code will provide below output.

textview

 43. SD card is available on device

Method checks if SDcard is available on device.

Parameter:

mContext (Pass application context)

Returns:

This method returns boolean value.

How to use:

boolean available = Common.​isSDCardAvailable(mContext);

44. Show Share Dialog

This method is used to open share dialog.

Parameters:

mContext (Pass application context)

strTitle (Title of dialog. It is optional.)

strUri (Local image uri path. It is optional.)

strShareText (Message to share. It is optional.)

strShareSubject (Subject to share. It is optional.)

Returns:

This method does not return any value.

How to use:

Common.openShareDialog(context, “Share Title”, “/mnt/sdcard/file.jpeg”, “Share Text”, “Share Subject”);

45. Change device profile (Silent or Vibrate or Normal)

This method is used to change device profile to Silent,Vibrate or Normal Mode.

Parameters:

mContext (Pass application context)

intMode (Pass mode in integer, i.e. 0 for silent, 1 for vibrate, 2 for normal)

Returns:

This method does not return any value.

How to use:

Silent

Common.chooseProfile(mContext,0);

Vibrate

Common.chooseProfile(mContext,1);

Normal

Common.chooseProfile(mContext,2);

46. Make bitmap rounded corner

This method is used to make bitmap to rounded corner or circled bitmap.

Parameters:

bitmap (Pass bitmap)

roundPixel (Pass radius in integer)

Returns:

This method returns bitmap object.

How to use:

Bitmap bitmap = Common.getRoundedCornerBitmap(bitmap , roundPixel);

47. Show Alert Dialog or Toast

This method is used to show AlertDialog or Toast message to user.

Parameters:

mContext (Pass application context)

strTitle (Pass dialog title)

strMessage (Pass Message)

toast (true for displaying toast, false for displaying dialog)

How to use:

To display dialog

Common.showAlertDialog(context, “App Name”, “Welcome User”, false);

To display toast

Common.showAlertDialog(context, “”, “Welcome User”, true);

48. Preventing double click

This method is used to prevent user from clicking multiple times.

Parameter:

view (Pass view to prevent click. i.e. button, textView, etc)

Returns:

This method does not return any value.

How to use:

Common.preventDoubleClick(btnLogin);

49. Turn Bluetooth or Wi-Fi ON/OFF

Wi-Fi

You can turn Wi-Fi ON or OFF forcefully using this method.

Parameters:

mContext (Pass application context)

action (pass ON or OFF string as action)

Returns:

This method does not return any value.

How to use:

Common.onWifi(mContext, action);

Bluetooth

You can turn Bluetooth ON or OFF forcefully using this method.

Parameters:

action (pass ON or OFF string as action)

Returns:

This method does not return any value.

How to use:

Common.onBluetooth(action);

50. Capture Image from camera

This method is used to capture image from camera.
Note: Call Common.onSaveInstanceState(Bundle) from onSaveInstanceState and onRestoreInstanceState(Bundle) from onRestoreInstanceState of activity.

Parameters:

mContext (Pass application context)

CAMERA_CAPTURE_IMAGE_REQUEST_CODE (request code for capturing image)

camera (“Front” or “Back” to open front or back camera)

How to use:

Front camera

Common.captureImage(mContext, 123, “Front”);

Back camera

Common.captureImage(mContext, 123, “Back”);

51. Pick Image

This method is used to pick image from gallery.

Parameters:

mContext (Pass application context)
CAMERA_PICK_IMAGE_REQUEST_CODE (request code to pick image)

How to use:

Common.pickImage(mContext , 234);

52. Preview Captured Image

This method is used to preview captured image.

Parameter:

ivImagePreview (imageView to preview image)

How to use:

Common.previewCapturedImage(ivImagePreview);

53. Record Video

This method is used to record video.
Note: Call Common.onSaveInstanceState(Bundle) from onSaveInstanceState and onRestoreInstanceState(Bundle) from onRestoreInstanceState of activity.

Parameters:

mContext (Pass application context)
CAMERA_CAPTURE_VIDEO_REQUEST_CODE (request code for recording video)
camera (“Front” or “Back” to open front or back camera)

How to use:

Using front camera

Common.recordVideo(mContext, 123, “Front”);

Using back camera

Common.recordVideo(mContext, 123, “Back”);

54. Pick Video

This method is used to pick video from gallery. A lso refer getPath() method.

Parameters:

mContext (Pass application context)
CAMERA_PICK_VIDEO_REQUEST_CODE (request code to pick video)

How to use:

Common.pickVideo(mContext, 234);

55. Preview Captured Video

By this method you can preview captured image.

Parameter:

videoPreview (VideoView in which you want to play Video)

How to use:

Common.previewVideo(videoPreview);

56. Get path of picked image or video (for all versions)

By this method you can get path of images, videos and documents from all versions of android.

Parameters:

mContext (Pass application context)
uri (uri you get in onActivityResult() i.e. Uri fileUri = data.getData();)

How to use:

Common.getPath(mContext, fileUri);

57. Integrating social platforms

Note: For a complete activity implementation, look at Common Activity below step 9. If you want Skills from linkedin, follow from S tep 9.

Follow the steps below to integrate L inkedIn, Twitter, Facebook, Google Plus.

1) Create a Class that implements D ialog Listener i n a ctivity w hich is Response listener

For e.g.

private final class ResponseListener implements DialogListener {
  @Override
  public void onComplete(Bundle values) {
  // Do what you want on completion of social login
  }
  @Override
  public void onError(SocialAuthError error) {
    error.printStackTrace();
  }
  @Override
  public void onCancel() {
  }
  @Override
  public void onBack() {
  }
}

2) Create new SocialAuthAdapter in o nCreate of Activity

SocialAuthAdapter adapter = new SocialAuthAdapter(new ResponseListener());

3) Call authorization for social site o n Click of Button

// You can replace LINKEDIN with FACEBOOK, TWITTER OR GOOGLEPLUS
adapter.authorize(mContext, SocialAuthAdapter.Provider.LINKEDIN);

4) To Sign out on S ign Out button click

adapter.signOut(mContext, SocialAuthAdapter.Provider.LINKEDIN.toString());

5) To post messages on Facebook, LinkedIn and Twitter

a) Create Class that implements SocialAuthListener<Integer> i n activity.

For e.g.

private final class MessageListener implements SocialAuthListener<Integer> {
  @Override public void onExecute(String provider, Integer status) {
    if (status.intValue() == 200 || status.intValue() == 201 || status.intValue() == 204)
      // "Message posted on" + provider
    else
      // "Message not posted" + provider
  }
  @Override
  public void onError(SocialAuthError e) {
    e.getInnerException().printStackTrace();
  }
}

b) Call update Status o n Click of Button

adapter.updateStatus("Hi Test Status Update @" + Calendar.getInstance().getTimeInMillis(), new MessageListener(), false);

6) To post image on Facebook and Twitter

a) Create Class that implements SocialAuthListener<Integer>

For e.g.

private final class UploadImageListener implements SocialAuthListener<Integer> {
  @Override
  public void onExecute(String provider, Integer t) {
    if (status.intValue() == 200 || status.intValue() == 201 || status.intValue() == 204)
      // "Message posted on" + provider
    else
      // "Message not posted" + provider
  }
  @Override
  public void onError(SocialAuthError e) {
    e.getInnerException().printStackTrace();
  }
}

b) Call upload image o n Click of Button

Bitmap bitmap = Common.drawableTobitmap(CommonActivity.this, R.drawable.facebook);
try {
  adapter.uploadImageAsync("Image Message", "icon.png", bitmap, 0, new UploadImageListener());
} catch (Exception e) {
  e.printStackTrace();
}

7) Get profile of social user

a) Create Class that implements SocialAuthListener<Profile> i n activity

For e.g.

private final class ProfileDataListener implements SocialAuthListener<Profile> {
    @Override
    public void onExecute(String provider, Profile profileMap) {
        // Get Details of profile
        Log.d("Validate ID = " , profileMap.getValidatedId());
        Log.d("First Name = " , profileMap.getFirstName());
        Log.d("Last Name = " , profileMap.getLastName());
        Log.d("Email = " , profileMap.getEmail());
        Log.d("Gender = " , profileMap.getGender());
        Log.d("Country = " , profileMap.getCountry());
        Log.d("Language = " , profileMap.getLanguage());
        Log.d("Location = " , profileMap.getLocation());
        Log.d("Profile Image URL = " , profileMap.getProfileImageURL());
    }

    @Override
    public void onError(SocialAuthError e) {
        e.printStackTrace();
    }
}

b) Call get profile o n Click of Button

adapter.getUserProfileAsync(new ProfileDataListener());

8) Get contacts list

a) Create Class that implements SocialAuthListener<List<Contact>> i n activity

For e.g.

private final class ContactDataListener implements SocialAuthListener<List<Contact>> {
    @Override
    public void onExecute(String provider, List<Contact> contactsList) {
        for( i = 0 ; i < contactsList.size() ; i++) {
            Contact contact =contactsList.get(i);
            Log.d("Contact", "Display Name = " + contact.getDisplayName());
             Log.d("Contact", "Name = " + contact.getFirstName()+” ”+contact.getLastName());
             Log.d("Contact", "Contact ID = " + contact.getId());
             Log.d("Contact", "Profile URL = " + contact.getProfileUrl());
             Log.d("Contact", "Profile Image URL = " + contact.getProfileImageURL());
             Log.d("Contact", "Email = " + contact.getEmail());
        }
    }

    @Override
    public void onError(SocialAuthError e) {
        e.printStackTrace();
    }
}

b) Call get Contact List o n Click of Button

adapter.getContactListAsync(new ContactDataListener());

9) Getting skills from linkedin

You can refer documentation for this. You will find the sample code of it on page no 24 of it. However, we’re going to cover this feature in a separate post.

58. Adding ripple effect

You can apply ripple effect to button, textview, etc. Just add following code to your xml file.

<com.andexert.library.RippleView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    ripple:rv_centered="false">

    <Button
        android:id="@+id/text5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="#00cc99"
        android:padding="30dp"
        android:text="Ripple Effect 3"
        android:textColor="@android:color/white"
        android:textSize="30sp" />
</com.andexert.library.RippleView>
You can also add below xml attributes.
ripple:rv_alpha [integer def:90 0-255] i.e. Alpha of the ripple
ripple:rv_framerate [integer def:10] i.e. Frame rate of the ripple animation
ripple:rv_rippleDuration [integer def:400] i.e. Duration of the ripple animation
ripple:rv_ripplePadding [dimension def:0] i.e. Add a padding to the ripple
ripple:rv_color [color def:@android:color/white] i.e. Color of the ripple
ripple:rv_centered [boolean def:false] i.e. Center ripple in the child view
ripple:rv_type [enum (simpleRipple, doubleRipple) def:simpleRipple] i.e. Simple or double ripple
ripple:rv_zoom [boolean def:false] i.e. Enable zoom animation
ripple:rv_zoomDuration [integer def:150] i.e. Duration of zoom animation
ripple:rv_zoomScale [float def:1.03] i.e. Scale of zoom animation

59. Check if website url is valid or not

Method is used to check website url is valid or not.

Parameter:

strUrl (website url as string)

Returns:

True i f website address is valid, otherwise f alse.

How to use:

boolean valid = Common.isWebsiteUrlValid (strUrl);

60. Get all contacts that have email address

Method is used to get contacts that have email address from contact book.

Parameter:

mContext(Pass application context).

Returns:

ArrayList of string with name and email as comma separated. i.e. name, n ame@name.com

How to use:

ArrayList<String> strContacts = Common.getNameEmailDetails(context);

61. Get bitmap of view (ScreenShot)

Used to get bitmap of layout.

Parameter:

View (view you want image of ie. : Layout, Views, etc).

Returns:

Bitmap of view.

How to use:

Bitmap screenShot = Common.captureView(textView);

62. Pick Color from ImageView

Used to pick color from image.Pass x, y and view from onTouch of ImageView onTouch Listener.

Parameters:

View (image view from which color is to be picked).

x (X-position of touch)

y (Y-position of touch)

Returns:

Color in integer format.

How to use:

int color = Common.pickColor(view, x, y);

63. Get File Size

Used to get size of file.

Parameters:

mContext (Pass application context)

strUrl (Pass url of file)

Return:

This method does not return anything. How to use: getRemoteFileSize(mContext, strUrl);

64. Download File

Used to download any file.

Parameters:

mContext (Pass application context)

strUrl (Url of file as string)

fileName (Filename with extension i.e. image.jpg)

Returns:

This method does not return anything.

How to use:

downloadRemoteFile(mContext, strUrl, fileName);

 

So this are the methods that we have covered in this SDK. We hope that it will be helpful to you. Feel free to provide your suggestions on this.

Disclaimer: We have taken enough care of quality while developing this library. It still might have some issues. So use it at your own risks. You can post the issues you find or suggestions on GitHub or our blog. We will do our best to make it better for you. Happy coding!

Avatar for Multidots
Author : Multidots
Multidots is full service enterprise software development company with services revolving around consulting, enterprise-grade custom application development, custom mobile and cloud applications to automated and manual testing. We are proud to have served mid-sized to large enterprises including Fortune 500 Companies in our clientele.

Comments

Leave a Reply

How can we help you?

Submit your Business Enquiry here and we will get in touch shortly.

Contact Us
X

Quick Contact

I give my consent to the storage and processing of my personal data by Multidots as per their privacy policy compliance.