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]