Android Programming : Adding minutes to time in hh:mm a format

Hi Guys, In some situation, we want to add some minutes to the predefined time range such as in my case, I want to add minutes {0,15,30,60,120,240} to my existing time range to perform some activity. Below is the code that implements the above behavior:

Below code is self explanatory:

//Global Variable

 private int[] iToincrement = {0,15,30,60,120,240};
 private static int _incCount = 0;
 private String strNewTime = null;

// call

for (_incCount = 0 ;  _incCount<iToincrement.length; _incCount++)
  {
      strNewTime = GetIncreasedTime("8:59 AM", iToincrement[_incCount]);
      // play with the new time in the variable strNewTime
  } 

//definition of GetIncreasedTime function

public String GetIncreasedTime(String strStartTime, int iMinute)
 {

  String[] hm = strStartTime.split(":");
  int hour = Integer.parseInt(hm[0]);
  String strMinWPMAM = hm[1];
  
  String[] minAMPM = strMinWPMAM.split(" ");
  int Min = Integer.parseInt(minAMPM[0]);
  String strPMAM = minAMPM[1];  

  int itotaltime = hour * 60 + Min;
  itotaltime += iMinute; 

  while (itotaltime < 0) 
  {   
    itotaltime += 1440;     
  }

  int nh = (itotaltime / 60) % 24;  
  int nm = itotaltime % 60;
  
  if (nh>=12)
  {
   strPMAM="PM";
  }else
  {
   strPMAM="AM";
  }  
    
  SimpleDateFormat sdf = new SimpleDateFormat("hh:mm", Locale.getDefault());
  Date DtNewTime;
  
  try {
   DtNewTime = sdf.parse(nh+":"+nm);
   Toast.makeText(MainActivity.this, "text : " + DtNewTime , Toast.LENGTH_LONG).show();
   return sdf.format(DtNewTime)+ " " + strPMAM;
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
  return "1";  
 }

Android Programming: Function for Time comparison

I have written below function to find if the current android system time is before/after/equal to the given time.

Below is the code from my MainActivity class which is self explanatory:

package com.aslsoft.pocapp;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

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

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);  
  
  TextView tv = (TextView) findViewById(R.id.tv);  
  tv.setText("Date Time : " + CompareTime("3:54 PM"));  
 }
 

 public String CompareTime(String strTimeToCompare)
 {
  Calendar cal = Calendar.getInstance(TimeZone.getDefault());
  int dtHour;
  int dtMin;
  int iAMPM;
  String strAMorPM=null;
  Date dtCurrentDate;
    
  SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa", Locale.getDefault());
  
  try {
   
   Date TimeToCompare = sdf.parse(strTimeToCompare);
   dtMin=cal.get(Calendar.MINUTE);
   dtHour=cal.get(Calendar.HOUR);   
   iAMPM=cal.get(Calendar.AM_PM);
   if (iAMPM == 1)
   {
    strAMorPM="PM";
   }
   
   if (iAMPM == 0)
   {
    strAMorPM="AM";
   }
   
   dtCurrentDate = sdf.parse(dtHour + ":" + dtMin + " " + strAMorPM);

   if(dtCurrentDate.after(TimeToCompare))
   {
    return "1";
   }
   if (dtCurrentDate.before(TimeToCompare))
   {
    return "2";
   }
   if (dtCurrentDate.equals(TimeToCompare))
   {
    return "3";
   }
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return "4";
 } 

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
}

			

Android Programming : Getting current Date and Time

To get date and time, we have used the Calendar class to get the instance to phone clock:

Calendar cal = Calendar.getInstance(TimeZone.getDefault());

TimeZone would be the one set in the phone.

 

Finally we have used SimpleDateFormat to get the time in the particular format:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a", Locale.getDefault());

 

Below is the source code from my MainActivity class:

 

package com.aslsoft.pocapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

import android.os.Bundle;
import android.app.Activity;
import android.text.format.Time;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  TextView tv = (TextView) findViewById(R.id.tv);
  Calendar cal = Calendar.getInstance(TimeZone.getDefault());
  
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a", Locale.getDefault());
  tv.setText("Date Time : " + cal.getTime().toLocaleString() + "\nTime :" + sdf.format(cal.getTime()) );
  
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

 

Result:

 

clip_image002

Android Programming: Reading Contact numbers and Email Addresses

Suppose we want to read all the contact numbers and their email IDs stored in the user’s address book.

I have written below method that will read all the contact numbers along with the email address and will display them in the EditText control.

To do so, in the below method, I have written two cursors. First cursor will read all the information related to phone contacts table. In the phone contacts table Contact_ID is the primary key. Second cursor will read all the information related to Emails based on the Contact_ID fetched from the first cursor. Contact_ID is also unique in the Email data. In short, Contact_ID is common unique column in the both the tables.

 

 public void GetMobileNumberAndEmail()
 {
  String strId=null;
  String pID="";
  TextView txtvw = (TextView) findViewById(R.id.tvDemo);
  ContentResolver cr = getContentResolver();
  Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " Asc");
  if (cur.getCount()>0)
  {
   while (cur.moveToNext())
   {
    strId = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));


    if (pID.compareTo(strId)!=0)
    {
     Cursor EmailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "= ?", new String[] { strId }, null);

     txtvw.append("-----------------------------\n");
     txtvw.append("\nName-->" + cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)) + "\n");
     txtvw.append("\nMobile-->" + cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) + "\n");

    if (EmailCur.getCount()>0)
    {
     while (EmailCur.moveToNext())
     {
      txtvw.append("\nEMail ID-->" + EmailCur.getString(EmailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)) + "\n");
     }

    EmailCur.close();
    }
    } else
     {
      txtvw.append("\nMobile-->" + cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) + "\n");
      txtvw.append("-----------------------------\n");
     }
    pID=strId;
   }
    cur.close();
  }
 }

 

Result:

 

clip_image002

Android Programming : Implementing Logging with Preferences

Hello techies, I am sharing you the class I wrote for recording logs in the android application.

Sometimes you need these logs to troubleshoot the application behavior. For this you have to have mechanism to write logs from every method/class in a file which you can refer later but the problem is you can not keep it recording for ever. It will eat-up the user’s memory and will also eat up the CPU. To minimize the loss, we can give preference to the users in the form of settings and they can turn logs on or off.

 

Below is the class called MyLogger which implements the methods to record the logs to user’s SDCard.

 

package com.aslsoft.pocapp;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.os.Environment;


public class MyLogger {

 /**
  *
  * This function is for writing the logs to sdcard.
  * This function will create file with the format "Log_[AppName]_DateToday.txt"
  * at the location /sdcard/[ApplicationName].
  * @param Class_functionName  Name of the Class and function from where to log the comments. Example : "MainActivity_OnCreate"
  * @param LogContent  The content that needs to be logged.
  * @author Mohd Aslam
  * @return It will not return any value.
  *
  */
 public void RecordLog(String Class_functionName, String LogContent )
 {
  FileWriter fw = null;
  File fLogFile;
  File rootsdcard = Environment.getExternalStorageDirectory();
  File dir = new File(rootsdcard.getAbsolutePath(),"/LogMyLocLogs");
  if (!dir.exists())
  {
   dir.mkdirs();
  }
  fLogFile = new File(dir, "MyLog.txt");

  try {
   fw = new FileWriter(fLogFile,true);

  } catch (IOException e) {
    // TODO Auto-generated catch block
   e.printStackTrace();
   try {
    fw.flush();
    fw.close();
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
  }
  try
  {
   fw.append("\n-----------------------------\n");
   fw.append("Class_Function Name:-++->" + Class_functionName);
   fw.append("\nLog:-->" + LogContent + "\n");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally
  {
  }
  try {
   fw.flush();
   fw.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


 

Add below to your manifest file. This permission will be required to write the log file to the sdcard.

 

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

 

Below is code that needs to be added to use the class and its method from the class to record the logs.

 

//declare global variable of the class MyLogger
 public MyLogger mylog=new MyLogger();

//Calling RecordLog method when the Logging option is enabled

if (GetPrefSettings("LoggingOn"))
{
    mylog.RecordLog("MainActivity_OnCreate", “My log”);
}

 

Below is the class where the setting (Log on/off) is implemented and the user preference is recorded. It has two functions to add and get preference. SharedPreferences class is used to set and get the preferences.

 

/**
 *
 */
package com.aslsoft.pocapp;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.Window;

/**
 * @author Mohd Aslam
 * Class for Application settings and preferences
 */
public class ApplicationSettings extends PreferenceActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.my_app_settings);
  CheckBoxPreference cbfSetting = (CheckBoxPreference) getPreferenceManager().findPreference(getResources().getString(R.string.Pref_IsLogEnabled));
  cbfSetting.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

   @Override
   public boolean onPreferenceChange(Preference preference, Object newValue) {
    // TODO Auto-generated method stub
    AddPrefSettings((Boolean) newValue);
    return true;
   }
  });

  cbfSetting.setChecked(GetPrefSettings(getResources().getString(R.string.Pref_IsLogEnabled)));
 }

//Method to add preferences
 public void AddPrefSettings(boolean IS_LOGGING_ON)
 {
  SharedPreferences MyPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  SharedPreferences.Editor MyPrefeditor = MyPreferences.edit();
  MyPrefeditor.putBoolean(getResources().getString(R.string.Pref_IsLogEnabled), IS_LOGGING_ON);
  MyPrefeditor.commit();
 }
 // Method to get Preferences
 public boolean GetPrefSettings(String strPrefKey)
 {
  SharedPreferences MyPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  return MyPreferences.getBoolean(strPrefKey, false);
 }

}

 

Below is the XML file for the settings screen:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <PreferenceCategory android:title="My Application Settings">
        <CheckBoxPreference
            android:summary="This will enable/disable the logs"
            android:title="Enable Logs"
            android:persistent="true"
            android:defaultValue="false"
            android:key="@string/Pref_IsLogEnabled"/>"
    </PreferenceCategory>
</PreferenceScreen>

 

 

 

Results:

My Applications Settings screen:

 

clip_image002

 

MyLog file in its destination directory:

 

clip_image002[5]

Android Programming: Reading Phone Contacts

In this Article, we will write code to read User’s name and phone contact number.

Below are the main activities that we need to incorporate in the code:

  1. Assigning Read access permission to read user’s contacts. Add the below line to AndroidManifest.xml file:

 

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

 

Or add the permissions from the AndroidMenifest.xml UI as shown below:

 

clip_image002

 

2.  Below is the code for activity_main.xml where we have defined TextView where we will display the User’s name and contact number.

 

 

<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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tvDemo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</LinearLayout>

 

 

3) Below is the Java code from MainActivity.java file: In this file, the function that is fetching the User’s contact details is GetMyPhoneContacts(). In this function, we have used a column list and a query which will return User’s contact details in the cursor.

Below is the information about the query method that we have used:

Cursor android.content.ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Query the given URI, returning a Cursor over the result set.

Parameters

uri

The URI, using the content:// scheme, for the content to retrieve.

projection

A list of which columns to return. Passing null will return all columns, which is inefficient.

selection

A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.

selectionArgs

You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.

sortOrder

How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. We have used Ascending order in this example.

Once the above query will return data in cursor, we will fetch the individual row in do while loop on the cursor. In the loop we are fetching the name and contact number of the user and appending it to the TextView.

 

 

 

package com.example.testapp;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.app.Activity;
import android.content.res.Configuration;
import android.database.Cursor;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        GetMyPhoneContacts();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_main);
		super.onConfigurationChanged(newConfig);
	}

	public void GetMyPhoneContacts()
	{
		String[] mProjection=new String[]
				{
					ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
					ContactsContract.CommonDataKinds.Phone.NUMBER
				};

		String strName = null;
		String strPhoneNumber = null;
		TextView txtvw = (TextView) findViewById(R.id.tvDemo);

		Cursor curPhoneContacts = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, mProjection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " Asc");

		curPhoneContacts.moveToFirst();

		do
		{

			strName = curPhoneContacts.getString(curPhoneContacts.getColumnIndex(Contacts.DISPLAY_NAME));
			strPhoneNumber = curPhoneContacts.getString(curPhoneContacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

			txtvw.append("\nName-->" + strName + "\n");
			txtvw.append("Phone Number-->" + strPhoneNumber + "\n\n\n");

		}while (curPhoneContacts.moveToNext());
		curPhoneContacts.close();
	}

}

 

 

 

Result:

 

 

 

clip_image002[6]

Android Programming : Screen orientation–Portrait / Landscape

Every mobile screen have two orientations, one is Portrait and the other is Landscape.

Whenever you will run your application on the mobile device, you can see it in either orientations. You may want to have different screen layout in the different screen orientations.

Portrait Layout:

 

image

 

Landscape Layout:

 

image

 

Now to make your App screen to work in both orientations as expected, please follow the below steps:

  1. As shown in the below screenshot, under “res” folder, create a new folder with the name “layout-land”, -land appended for landscape orientation.
  2. For landscape orientation, create layout xml under “layout-land” folder with the same name as of the layout xml under “layout” folder. Note that name of the xml file in layout and layout-land folder should be same.

image

 

Having done the above steps, now when you will run your Android App in the Simulator or the actual device, when you will keep the screen in the portrait orientation, layout xml under layout folder will be picked up and when you will put the screen in the landscape mode, layout xml under layout-land folder will be picked up.

Note: To change the orientation of the screen in simulator, press Ctrl + F11.

Example from my latest App: Below are the screenshots from both the orientations. Please note the placement of the UI components in both the screens. I have created separate XML for the modes.

In Portrait mode: 

image

In Landscape mode:

image