5252
5353public class Helpers {
5454
55- public static Spannable highlightSubstringYellow (Context context , String text ,
56- String searchString , boolean sent ) {
57- // Find all occurrences of the substring in the text.
58- List <Integer > startIndices = new ArrayList <>();
59- int index = text .toLowerCase ().indexOf (searchString .toLowerCase ());
60- while (index >= 0 ) {
61- startIndices .add (index );
62- index = text .indexOf (searchString , index + searchString .length ());
63- }
64-
65- // Create a SpannableString object.
66- SpannableString spannableString = new SpannableString (text );
67-
68- // Set the foreground color of the substring to yellow.
69- BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan (
70- context .getColor (R .color .md_theme_inversePrimary ));
71- for (int startIndex : startIndices ) {
72- spannableString .setSpan (backgroundColorSpan , startIndex , startIndex + searchString .length (),
73- Spanned .SPAN_EXCLUSIVE_EXCLUSIVE );
74- }
75-
76- return spannableString ;
77- }
78- public static long generateRandomNumber () {
79- Random random = new Random ();
80- return random .nextInt (Integer .MAX_VALUE );
81- }
82-
83- public static int dpToPixel (float dpValue ) {
84- float density = Resources .getSystem ().getDisplayMetrics ().density ;
85- return (int ) (dpValue * density );
86- }
87-
88- public static int getRandomColor () {
89- Random random = new Random ();
90- int r = random .nextInt (256 );
91- int g = random .nextInt (256 );
92- int b = random .nextInt (256 );
93- int color = r << 16 | g << 8 | b ;
94-
95- return generateColor (color );
96- }
97-
98- public static String [] convertSetToStringArray (Set <String > setOfString )
99- {
100- // Create String[] of size of setOfString
101- String [] arrayOfString = new String [setOfString .size ()];
102-
103- // Copy elements from set to string array
104- // using advanced for loop
105- int index = 0 ;
106- for (String str : setOfString )
107- arrayOfString [index ++] = str ;
108-
109- // return the formed String[]
110- return arrayOfString ;
111- }
112-
11355 public static boolean isShortCode (String address ) {
11456 if (address .length () < 4 )
11557 return true ;
@@ -118,34 +60,13 @@ public static boolean isShortCode(String address) {
11860 return !PhoneNumberUtils .isWellFormedSmsAddress (address ) || matcher .find ();
11961 }
12062
121- public static byte [] generateRandomBytes (int length ) {
122- SecureRandom random = new SecureRandom ();
123- byte [] bytes = new
124-
125- byte [length ];
126- random .nextBytes (bytes );
127- return bytes ;
128- }
129-
130- public static String getFormatCompleteNumber (Context context , String address , String defaultRegion ) {
131- try (Cursor cursor = NativeSMSDB .fetchByAddress (context , address )) {
132- if (cursor .moveToFirst ()) {
133- int recipientIdIndex = cursor .getColumnIndexOrThrow ("address" );
134- address = cursor .getString (recipientIdIndex );
135- }
136- cursor .close ();
137- } catch (Exception e ) {
138- e .printStackTrace ();
139- }
140-
141- return address ;
142- }
143-
14463 public static String getFormatCompleteNumber (String data , String defaultRegion ) {
14564 data = data .replaceAll ("%2B" , "+" )
14665 .replaceAll ("-" , "" )
14766 .replaceAll ("%20" , "" )
148- .replaceAll (" " , "" );
67+ .replaceAll (" " , "" )
68+ .replaceFirst ("^0+" , "" );
69+
14970 if (data .length () < 5 )
15071 return data ;
15172 PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil .getInstance ();
@@ -157,9 +78,10 @@ public static String getFormatCompleteNumber(String data, String defaultRegion)
15778
15879 return "+" + countryCode + nationalNumber ;
15980 } catch (NumberParseException e ) {
160- // e.printStackTrace();
16181 if (e .getErrorType () == NumberParseException .ErrorType .INVALID_COUNTRY_CODE ) {
162- data = outputNumber .replaceAll ("sms[to]*:" , "" );
82+ data = outputNumber
83+ .replaceAll ("sms[to]*:" , "" )
84+ .replaceFirst ("^0+" , "" );
16385 if (data .startsWith (defaultRegion )) {
16486 outputNumber = "+" + data ;
16587 } else {
@@ -228,35 +150,6 @@ public static String getFormatNationalNumber(String data, String defaultRegion)
228150 return data ;
229151 }
230152
231- // public static String formatDateExtended(Context context, long epochTime) {
232- // long currentTime = System.currentTimeMillis();
233- // long diff = currentTime - epochTime;
234- //
235- // Date currentDate = new Date(currentTime);
236- // Date targetDate = new Date(epochTime);
237- //
238- // SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.getDefault());
239- // SimpleDateFormat fullDayFormat = new SimpleDateFormat("EEEE", Locale.getDefault());
240- // SimpleDateFormat shortDayFormat = new SimpleDateFormat("EEE", Locale.getDefault());
241- // SimpleDateFormat shortMonthDayFormat = new SimpleDateFormat("MMM d", Locale.getDefault());
242- //
243- //// if (diff < DateUtils.HOUR_IN_MILLIS) { // less than 1 hour
244- //// return DateUtils.getRelativeTimeSpanString(epochTime, currentTime, DateUtils.MINUTE_IN_MILLIS).toString();
245- //// }
246- // if (diff < DateUtils.DAY_IN_MILLIS) { // less than 1 day
247- // return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_SHOW_TIME);
248- // } else if (isSameDay(currentDate, targetDate)) { // today
249- // return timeFormat.format(targetDate);
250- // } else if (isYesterday(currentDate, targetDate)) { // yesterday
251- // return context.getString(R.string.single_message_thread_yesterday) + " • " + timeFormat.format(targetDate);
252- // } else if (isSameWeek(currentDate, targetDate)) { // within the same week
253- // return fullDayFormat.format(targetDate) + " • " + timeFormat.format(targetDate);
254- // } else { // greater than 1 week
255- // return shortDayFormat.format(targetDate) + ", " + shortMonthDayFormat.format(targetDate)
256- // + " • " + timeFormat.format(targetDate);
257- // }
258- // }
259-
260153 public static String formatDateExtended (Context context , long epochTime ) {
261154 long currentTime = System .currentTimeMillis ();
262155 long diff = currentTime - epochTime ;
@@ -281,13 +174,6 @@ public static String formatDateExtended(Context context, long epochTime) {
281174 }
282175 }
283176
284- private static boolean isSameDay (Date date1 , Date date2 ) {
285- SimpleDateFormat dayFormat = new SimpleDateFormat ("yyyyDDD" , Locale .getDefault ());
286- String day1 = dayFormat .format (date1 );
287- String day2 = dayFormat .format (date2 );
288- return day1 .equals (day2 );
289- }
290-
291177 private static boolean isYesterday (Date date1 , Date date2 ) {
292178 SimpleDateFormat dayFormat = new SimpleDateFormat ("yyyyDDD" , Locale .getDefault ());
293179 String day1 = dayFormat .format (date1 );
@@ -309,21 +195,6 @@ private static boolean isSameWeek(Date date1, Date date2) {
309195 return week1 .equals (week2 );
310196 }
311197
312- // public static String formatDate(Context context, long epochTime) {
313- // long currentTime = System.currentTimeMillis();
314- // long diff = currentTime - epochTime;
315- //
316- // if (diff < DateUtils.HOUR_IN_MILLIS) { // less than 1 hour
317- // return DateUtils.getRelativeTimeSpanString(epochTime, currentTime, DateUtils.MINUTE_IN_MILLIS).toString();
318- // } else if (diff < DateUtils.DAY_IN_MILLIS) { // less than 1 day
319- // return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_SHOW_TIME);
320- // } else if (diff < DateUtils.WEEK_IN_MILLIS) { // less than 1 week
321- // return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY);
322- // } else { // greater than 1 week
323- // return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE);
324- // }
325- // }
326-
327198 public static String formatDate (Context context , long epochTime ) {
328199 long currentTime = System .currentTimeMillis ();
329200 long diff = currentTime - epochTime ;
@@ -352,17 +223,6 @@ public static String formatDate(Context context, long epochTime) {
352223 return null ;
353224 }
354225
355- public static String formatLongDate (long epochTime ) {
356- // Create a date object from the epoch time
357- Date date = new Date (epochTime );
358-
359- // Create a SimpleDateFormat object with the desired format
360- SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd, h:mm a" , Locale .getDefault ());
361-
362- // Format the date and return the string
363- return formatter .format (date );
364- }
365-
366226 public static String getUserCountry (Context context ) {
367227 String countryCode = null ;
368228
@@ -379,57 +239,6 @@ public static String getUserCountry(Context context) {
379239 return String .valueOf (PhoneNumberUtil .getInstance ().getCountryCodeForRegion (countryCode ));
380240 }
381241
382- public static int getColor (Context context , String input ) {
383- int sDefaultColor = context .getResources ().getIntArray (R .array .letter_tile_colors )[0 ];
384- // int sDefaultColor = context.getColor(defaultColor);
385- if (TextUtils .isEmpty (input )) {
386- return sDefaultColor ;
387- }
388- TypedArray sColors = context .getResources ().obtainTypedArray (R .array .letter_tile_colors );
389- // String.hashCode() implementation is not supposed to change across java versions, so
390- // this should guarantee the same email address always maps to the same color.
391- // The email should already have been normalized by the ContactRequest.
392- final int color = Math .abs (input .hashCode ()) % sColors .length ();
393- return sColors .getColor (color , sDefaultColor );
394- }
395-
396- public static int generateColor (int input ) {
397- int hue ;
398- int saturation = 100 ;
399- int value = 60 ; // Reduced value component for darker colors
400-
401- hue = Math .abs (input * 31 % 360 );
402- // Convert the HSV color to RGB and return the color as an int
403- float [] hsv = {hue , saturation , value };
404- int color = Color .HSVToColor (hsv );
405- return color ;
406- }
407-
408- public static int generateColor (String input ) {
409- int hue ;
410- int saturation = 100 ;
411- int value = 60 ; // Reduced value component for darker colors
412-
413- if (input .length () == 0 ) {
414- // Return a default color if the input is empty
415- hue = 0 ;
416- } else if (input .length () == 1 ) {
417- // Use the first character of the input to generate the hue
418- char firstChar = input .charAt (0 );
419- hue = Math .abs (firstChar * 31 % 360 );
420- } else {
421- // Use the first and second characters of the input to generate the hue
422- char firstChar = input .charAt (0 );
423- char secondChar = input .charAt (1 );
424- hue = Math .abs ((firstChar + secondChar ) * 31 % 360 );
425- }
426-
427- // Convert the HSV color to RGB and return the color as an int
428- float [] hsv = {hue , saturation , value };
429- int color = Color .HSVToColor (hsv );
430- return color ;
431- }
432-
433242 public static boolean isBase64Encoded (String input ) {
434243 try {
435244 byte [] decodedBytes = Base64 .decode (input , Base64 .DEFAULT );
@@ -444,82 +253,6 @@ public static boolean isBase64Encoded(String input) {
444253 }
445254 }
446255
447- public static void highlightLinks (TextView textView , String text , int color ) {
448- if (text == null )
449- return ;
450- // Regular expression to find URLs in the text
451- // String urlPattern = "((mailto:)?[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)" +
452- // "|((\\+?[0-9]{1,3}?)[ \\-]?)?([\\(]{1}[0-9]{3}[\\)])?[ \\-]?[0-9]{3}[ \\-]?[0-9]{4}" +
453- // "|(https?://)?([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-zA-Z]{2,}(/[\\w\\.-]+)*" +
454- // "|(https?://)?([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-zA-Z]{2,}(/[\\w\\.-]+)*(/\\S*)*(\\?[^ ]*#[^ ]*)/?";
455-
456- SpannableString spannableString = new SpannableString (text );
457-
458- String [] splitString = text .split ("\\ s" );
459- for (int i =0 , length =0 ; i <splitString .length ; ++i ){
460- final String _string = splitString [i ];
461- length += _string .length () + 1 ; // one for the space removed
462-
463- final int start = length - _string .length ()-1 ;
464- final int end = length -1 ;
465-
466- if (Patterns .WEB_URL .matcher (_string ).matches ()) {
467- ClickableSpan clickableSpan = new ClickableSpan () {
468- @ Override
469- public void onClick (View widget ) {
470- Intent intent = new Intent (Intent .ACTION_VIEW ,
471- Uri .parse ((_string .startsWith ("http://" ) ||
472- _string .startsWith ("https://" )) ? _string : "https://" + _string ));
473- intent .setFlags (FLAG_ACTIVITY_NEW_TASK );
474- widget .getContext ().startActivity (intent );
475- }
476- };
477- spannableString .setSpan (clickableSpan , start , end ,
478- Spannable .SPAN_EXCLUSIVE_EXCLUSIVE );
479- spannableString .setSpan (new ForegroundColorSpan (color ), start , end ,
480- Spannable .SPAN_EXCLUSIVE_EXCLUSIVE );
481- }
482- else if (Patterns .EMAIL_ADDRESS .matcher (_string ).matches ()) {
483- ClickableSpan clickableSpan = new ClickableSpan () {
484- @ Override
485- public void onClick (View widget ) {
486- Intent intent = new Intent (Intent .ACTION_SENDTO );
487- intent .setFlags (FLAG_ACTIVITY_NEW_TASK );
488- intent .setData (Uri .parse ("mailto:" + _string ));
489- widget .getContext ().startActivity (intent );
490- }
491- };
492- try {
493- spannableString .setSpan (clickableSpan , start , length , Spannable .SPAN_EXCLUSIVE_EXCLUSIVE );
494- spannableString .setSpan (new ForegroundColorSpan (color ), start , end ,
495- Spannable .SPAN_EXCLUSIVE_EXCLUSIVE );
496- } catch (Exception e ) {
497- e .printStackTrace ();
498- }
499- }
500- else if (_string .matches (
501- "\\ (*\\ +*[1-9]{0,3}\\ )*-*[1-9]{0,3}[-. \\ /]*\\ (*[2-9]\\ d{2}\\ )*[-. \\ /]*\\ d{3}[-. \\ /]*\\ d{4} *e*x*t*\\ .* *\\ d{0,4}" +
502- "|[*#][\\ d\\ *]*[*#]" )) {
503- ClickableSpan clickableSpan = new ClickableSpan () {
504- @ Override
505- public void onClick (View widget ) {
506- Uri phoneNumberUri = Uri .parse ("tel:" + _string );
507- Intent dialIntent = new Intent (Intent .ACTION_DIAL , phoneNumberUri );
508- dialIntent .setFlags (FLAG_ACTIVITY_NEW_TASK );
509- widget .getContext ().startActivity (dialIntent );
510- }
511- };
512- spannableString .setSpan (clickableSpan , start , end , Spannable .SPAN_EXCLUSIVE_EXCLUSIVE );
513- spannableString .setSpan (new ForegroundColorSpan (color ), start , end ,
514- Spannable .SPAN_EXCLUSIVE_EXCLUSIVE );
515- }
516- }
517-
518- textView .setMovementMethod (LinkMovementMethod .getInstance ());
519- textView .setText (spannableString );
520- }
521-
522-
523256 public static boolean isSameMinute (Long date1 , Long date2 ) {
524257 java .util .Date date = new java .util .Date (date1 );
525258 Calendar currentCalendar = Calendar .getInstance ();
0 commit comments