Check if internet is available in Android

Many time in the Android app we need to fetch data from any webservices in JSON or XML or in any other format but during unavailability of internet we need to display specific message like no internet available or show offline data.

For that we need to use ConnectivityManager system service as follows.

ConnectivityManager cm = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);

Then we can get network information from above ConnectivityManager as follows using NetworkInfo.

NetworkInfo ni = cm.getActiveNetworkInfo();

Now this NetworkInfo have the following network states displyed in following table.

NetworkInfo.State CONNECTED
NetworkInfo.State CONNECTING
NetworkInfo.State DISCONNECTED
NetworkInfo.State DISCONNECTING
NetworkInfo.State SUSPENDED
NetworkInfo.State UNKNOWN

Now we have to check for the connected state of the network.

ni.getState() == NetworkInfo.State.CONNECTED;

From the above conclusion, finally we have come up with the following function that directly checks for the availability of the internet.

public boolean isNetworkAvailable() {
	ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo ni = cm.getActiveNetworkInfo();
	return ni != null && ni.getState() == NetworkInfo.State.CONNECTED;
}

Turn on and turn off flash light programmatically in Android

Most of times we need to use flash light of our Android device as torch so we have to start camera or other application. But Android provide access to the camera flash in our application so you can turn it on and off using code. Here I’ll show you how to turn on and off it programmatically.

First of all we need to check if the device has the flash light or not. For that we use following condition from PackageManager.

Here is the function for turn on the flash light.

Camera cam = null;
public void turnOnFlashLight() {
    try {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            cam = Camera.open();
            Parameters p = cam.getParameters();
            p.setFlashMode(Parameters.FLASH_MODE_TORCH);
            cam.setParameters(p);
            cam.startPreview();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Exception throws in turning on flashlight.", Toast.LENGTH_SHORT).show();
    }
}

And to turn of flashlight use following piece of code.

public void turnOffFlashLight() {
    try {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            cam.stopPreview();
            cam.release();
            cam = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Exception throws in turning off flashlight.", Toast.LENGTH_SHORT).show();
    }
}

Here we use Camera class for flashlight.

Here we need to add the following permission to the manifest file. The last one is not generally used in 3rd party apps, it is just use for testing in system apps as per docs.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.HARDWARE_TEST" />

Here you can download full code from github: Flashligh Demo

You can download demo app from Google Play: Flashlight Demo

Get name of the month from the number of the month Java

Many times we need to use month name to display date in well formed manner. I encounter this issue while developing Android application that use Android datepicker. It returns me the number of the month between 0 to 11 [I thought it would be 1-12]. But for display I need the name of the month.

For that I found one Java class that can convert integer number to name [I am too lazy to write an array that can do the work for me]. And the class DateFormatSymbols can convert it the following way. I just made a method so everyone[like me !!!] can copy-paste it to their project.

public String getMonthForInt(int num) {
    String month = "wrong";
    DateFormatSymbols dfs = new DateFormatSymbols();
    String[] months = dfs.getMonths();
    if (num >= 0 && num <= 11 ) {
        month = months[num];
    }
    return month.toLowerCase();
}

How to check current sound profile in Android

Many times in Android development, we need to check the current sound profile. Like it is in normal mode, vibrate mode or silent mode. So for that in Android, they provide AudioManager class which have method that return the current sound profile. Below is the example of it.

AudioManager profileCheck = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

if (profileCheck.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)
    Toast.makeText(getApplicationContext(), "Normal", Toast.LENGTH_LONG).show();
else if (profileCheck.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)
    Toast.makeText(getApplicationContext(), "Vibrate", Toast.LENGTH_LONG).show();
else if (profileCheck.getRingerMode() == AudioManager.RINGER_MODE_SILENT)
    Toast.makeText(getApplicationContext(), "Silent", Toast.LENGTH_LONG).show();

According to the sound profile you can manage your further actions.

Validation in Java/Android

Many time during my Android development, I need to verify email address, username, password or any specific requirements. Most of times it needs when I am building registration form or login form. So I made the function that takes first argument as string on which validation is needed and pattern [Regular Expression] that decides first argument is valid or invalid.

Here I use two main java class

Here Pattern class compile the regular expression and then Matcher class perform match operation against given String using compiled pattern. Here is the function for that.

	public Boolean validate(String text, String regex)	{
		Pattern pattern;	
		Matcher matcher;
		pattern = Pattern.compile(regex);
    	matcher = pattern.matcher(text);
    	if(matcher.matches())	{
    		return true;
    	}
    	else	{
    		return false;
    	}
	}

Here you can see that the function validate validates the String text against the regex using Pattern and Matcher class. I attached the example of email validation below, but you can use any validation by just providing their regular expression.

Download example of email validation with comments here : https://www.mediafire.com/view/vgw8pdf5db9ygzu/Validation.java

References :

PDO connection class in PHP [OOP approach with singleton pattern]

Now a days in PHP and Mysql connection after deprecation of Mysql, PDO [PHP Data Objects] and Mysqli is the best choice. In that PDO is widely used in new frameworks because it has more benefits than Mysql and Mysqli. Here is the list of features of PDO.

  • Have dirvers for 12 different databases [list them using print_r(PDO::getAvailableDrivers());]
  • OOP approach
  • Named parameters
  • Object mapping
  • Prepared statements
  • Fast performance
  • Stored procedures

Now here I am showing you the class of database connection that I used for my work. In that I use singleton pattern that eliminate the chances of having more than one instance of the class object in memory.

<?php

class database
{
    public $dbc;
    private static $instance;

    private function __construct()
    {
        $this -> dbhc= new PDO('mysql:host=localhost;dbname=example', "root", "");
    }

    //singleton pattern
    public static function getInstance()
    {
        if (!isset(self::$instance))
        {
            $object = __CLASS__;
            self::$instance = new $object;
        }
        return self::$instance;
    }
}

?>

You can use above class using following example code.


//get database connector by calling static method of database class [singleton pattern]
$db = database::getInstance();


        
//insert operation
$sql = "insert into `user` (`username`, `password`, `fullname`, `email`) values (:username, :password, :fullname, :email)";    //named parameters

$query = $db -> dbc -> prepare($sql);

$result = $query -> execute(array(":username" => $username, ":password" => $password, ":fullname" => $fullname, ":email" => $email));    //named parameters value
             
if($result)
    echo "Insert Successfull.";
else
    echo "Insert Fail."


        
//update operation
$sql = "update `user` set `username` = ?,  `password` = ?, `fullname` = ?, `email` = ? where `user_id` = ?";    //prepared statements

$query = $db -> dbc -> prepare($sql);

$result = $query -> execute(array($username, $password, $fullname, $email, $user_id));   //prepared statements value
        
if($result)
    echo "Update Successfull.";
else
    echo "Update Failed.";



//delete operation
$sql = "delete from `user` where `user_id` = ?";   //prepared statements

$query = $db -> dbc -> prepare($sql);

$result = $query -> execute(array($user_id));   //prepared statements value
        
if($result)
    echo "Delete Successfull.";
else
    echo "Delete Failed.";



//select operation
$sql = "select * from `user` where `user_id` = ?";   //prepared statements

$query = $db -> dbc -> prepare($sql);
        
$query -> execute(array($user_id));   //prepared statements value
        
$query -> setFetchMode(PDO::FETCH_ASSOC); // [PDO::FETCH_NUM for integer key value]
        
$result = $query -> fetchAll();


Download database class file here : https://www.mediafire.com/view/lmmlosnf26v5lla/db_config.php

References :

How to delete folder with contents in it in PHP

Many times in PHP, we need to delete the folder containing subfolders and files. So we have to check for depth and according to that we have to delete files first and then folders. But if we don’t know the content of it then it will be very difficult task to delete it. I am working on some stuff that need to be delete once it is utilized so I make the function that check for the subfolders and files and recursively delete the contents of it.

Here is the function for delete.

function delFolder($folder) 
{ 
	foreach(glob($folder . '/*') as $file) 
	{ 
		if(is_dir($file)) 
			delFolder($file); 
		else 
			unlink($file); 
	} 
	rmdir($folder); 
}

Here delFolder is the function that perform delete task.

Here we use following of the PHP function.

  • glob — Find pathnames matching a pattern
  • is_dir — Tells whether the filename is a directory
  • unlink — Deletes a file
  • rmdir — Removes directory

Download the full example with comments here : https://www.mediafire.com/view/winyqdt2fr1jsll/delFolder.php

Set the wallpaper from code in Android

During android application you may need to set wallpaper using code, then you have to use following method.

public void setStream (InputStream data)

For that you need to include the following permission to your menifest file.

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

I’ve made the method that will directly set the wallpaper image specified in argument.

public void setWallpaper(String pathToImage)    {
    try {
        WallpaperManager wpm = WallpaperManager.getInstance(getApplicationContext());
	    InputStream ins = new URL("file://" + pathToImage).openStream();
	    wpm.setStream(ins);
	    Toast.makeText(getApplicationContext(), "Wallpaper has been set", Toast.LENGTH_SHORT).show();            
    } 
    catch (MalformedURLException e) {
        e.printStackTrace();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }     
}

Here we have to specify “file://” which specify the protocol which we use here. We can also use http, ftp, etc. Otherwise it throws “java.net.MalformedURLException: Protocol not found: ” exception.

IP address validation in javascript

In javascript, we have to do validation at client side. For that purpose we have regex [Regular Expression]. But for some complex or specific requirement we have to build some logic at our own. So here the function check whether the IP address enter in textbox is correct or not and return true or false accordingly.

Functino for IP validation in javascript.

Code :

function checkIpAdd(id)
{
	var ipAdd = document.getElementById(id).value;
	if(ipAdd.substr(0, 3) > 255 || ipAdd.substr(4, 3) > 255 || ipAdd.substr(8, 3) > 255 || ipAdd.substr(12, 3) > 255)	
                return false;
        else    return true;
}

Get Date and Time in Android

In Android, to get time and date you have to first create the object of calender then you can format it using simpledateformat class according to your need. At last it returns you a date and time as per your format in String return type.

Here is the sample code for getting date and time as string.

Code :

public String getDateTime()	{
	Calendar c = Calendar.getInstance(); 
	SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
	return df.format(c.getTime());
}