Android – All about Java

Date Time – How to add hours to date time string?

    public String addHoursToDate(String dateTime, int hoursToAdd) {
        // Convert string to Date
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        Date d = null;
        try {
            d = formatter.parse(dateTime);

            // Add milliseconds into Date
            long millisToAdd = TimeUnit.HOURS.toMillis(hoursToAdd);
            d.setTime(d.getTime() + millisToAdd);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return formatter.format(d);
    }

Date Time – How to get time difference?

DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");

try {
    Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
    Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");

    obj.printDifference(date1, date2);

} catch (ParseException e) {
    e.printStackTrace();
}

//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate) { 
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

    System.out.printf(
        "%d days, %d hours, %d minutes, %d seconds%n", 
        elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}

SQLite – SELECT query

    public ArrayList<ArrayList<String>> getUserList() {
        ArrayList<ArrayList<String>> userList = new ArrayList<ArrayList<String>>();
        try {
            db = sInstance.getReadableDatabase();
            sql = "SELECT * from users";

            if (db == null) {
                return userList;
            }

            Cursor cursor = db.rawQuery(sql, null);

            if (cursor.getCount() == 0) {
                cursor.close();
                return userList;
            }

            if (cursor.moveToFirst()) {
                do {
                    ArrayList<String> holder = new ArrayList<>();
                    holder.add(cursor.getString(0));  // first name
                    holder.add(cursor.getString(1));  // last name
                    holder.add(cursor.getString(2));  // active
                    userList.add(holder);
                } while (cursor.moveToNext());
            }

            return userList;
        } catch (Exception e) {
            return userList;
        }
    }

SQLite – Get a specific row

...
// Get last row
cursor.moveToPosition(cursor.getCount() - 1);

// Get value of last row
String firstName = cursor.getString(0);
...

SQLite – Migration

  • How to check if index exists
    protected boolean checkIndexExists(String indexName) {
        boolean result = false ;
        Cursor cursor = null ;

        try {
            cursor = db.rawQuery( "SELECT * FROM sqlite_master WHERE type = 'index' and name = ?", new String[]{ indexName });
            result = null != cursor && cursor.moveToFirst() ;
        } catch (Exception e){
            Log.e("checkIndexExists","checkIndexExists..." + e.getMessage()) ;
        } finally{
            if(null != cursor && !cursor.isClosed()){
                cursor.close() ;
            }
        }

        return result ;
    }
  • How to drop index
    • Has to drop table to drop index
    protected void dropIndex() {
        try {
            Boolean checkIndexExists = checkIndexExists("uniqueIndexName");
            if (checkIndexExists) {
                String sql = "DROP TABLE IF EXISTS "+ "tableName";
                db.execSQL(sql);

                // Re-create table
                reCreateTable();
            }
        } catch (Exception e) {
        }
    }

Be the first to comment

Leave a Reply

Your email address will not be published.


*