Problems in connecting to a WiFi network that has MAC Filtering enabled

Prerequisite: You should have given your device MAC address to the network admin.

You may have come across this issue while trying to connect your phone to a WiFi network that has MAC Filtering enabled.
Follow these steps to resolve it.

Tested on: Samsung Galaxy S10e

  1. Goto the troublesome network -> Manage network settings

2. Check what’s the value in MAC address type field. Most probably it should be set to Use randomized MAC(default). This could be a reason for not getting connected to the WiFi network.

3. Change it to Use device MAC

The problem should be resolved. 🙂

Custom TextView control with hovering(Objective-C version)

Hello again.
This time I’m going to explain about a custom textview control with hovering.

The scenario which directed me to build up a control like this as follows.
Let’s say you have a textview(max number of lines 1) with a limited width. When you set a lengthy text on it, it will automatically truncate some part of the text and add 3 dots(…) towards the end.

The solution which I proposed would work like this.
Say you have a textview with a lengthy text, when you tap and hold it, it’ll bring up the entire text(without any truncation) in a hover view/separate view.

Ex:

A textview with a lengthy text.

When you tap and hold the textview…

Now I’m going to the details of the actual implementation.

.h file

#import <UIKit/UIKit.h>

@interface CustomTextView : UITextView

@property(atomic, weak) UIViewController* currentViewController;
@property(atomic, strong) UIView* hoverView;

@end

.m file

#import <Foundation/Foundation.h>
#import "CustomTextView.h"
#import "UIHelper.h"

@implementation CustomTextView

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self)
        [self initialSetup];
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
        [self initialSetup];
    return self;
}

- (void)onLongPress:(UILongPressGestureRecognizer *) longPressGestureRecognizer {
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan)
    {
        if(longPressGestureRecognizer.view != nil){
            if ([longPressGestureRecognizer.view isKindOfClass:[UITextView class]]) {
                UITextView *textView = (UITextView*)longPressGestureRecognizer.view;
                
                self.currentViewController = self.window.rootViewController;
                
                NSString *text = textView.text;
                
                CGSize sizeRequired = [textView.text sizeWithAttributes:@{NSFontAttributeName :textView.font}];
                CGFloat widthRequired = sizeRequired.width;
                CGFloat widthAvailable = textView.bounds.size.width;
                if(widthRequired <= widthAvailable) return;
                
                [textView sizeToFit];
                
                CGFloat navigationBarHeight = 0;
                if(self.currentViewController.navigationController.navigationBar != nil) navigationBarHeight = self.currentViewController.navigationController.navigationBar.frame.size.height;
                
                CGFloat toolbarHeight = 0;
                UIToolbar *toolbar = [UIHelper findToolbar:self.currentViewController.view];
                if (toolbar != nil) toolbarHeight = toolbar.frame.size.height;
                
                CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
                CGFloat availableHeight = screenHeight - (navigationBarHeight + toolbarHeight);
                CGPoint currentRelativePoint = [self.currentViewController.view convertPoint:textView.frame.origin toView:nil];
                CGRect originalRect = textView.frame;
                CGFloat currentYPos = (currentRelativePoint.y + originalRect.size.height);
                
                UITextView *innerTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, originalRect.size.width, originalRect.size.height)];
                [innerTextView setFont:[UIFont systemFontOfSize:12]];
                [innerTextView setText:text];
                [innerTextView setFrame:CGRectMake(0, 0, originalRect.size.width, innerTextView.contentSize.height)];
                
                CGRect innerRect = innerTextView.frame;
                if ((availableHeight - currentYPos) >= innerRect.size.height)
                    self.hoverView = [[UIView alloc] initWithFrame:CGRectMake(originalRect.origin.x, (originalRect.origin.y + originalRect.size.height), innerRect.size.width, innerRect.size.height)];
                else
                    self.hoverView = [[UIView alloc] initWithFrame:CGRectMake(originalRect.origin.x, (originalRect.origin.y - innerRect.size.height), innerRect.size.width, innerRect.size.height)];
                
                [self.hoverView.layer setBorderColor:[UIColor purpleColor].CGColor];
                [self.hoverView.layer setBorderWidth:1];
                [self.hoverView.layer setCornerRadius:4];
                
                [self.hoverView addSubview:innerTextView];
                [textView.superview addSubview:self.hoverView];
            }
        }
    }
    else
    {
        if (longPressGestureRecognizer.state == UIGestureRecognizerStateCancelled
            || longPressGestureRecognizer.state == UIGestureRecognizerStateFailed
            || longPressGestureRecognizer.state == UIGestureRecognizerStateEnded)
        {
            if (self.hoverView != nil){
                UITextView *innerTextView = [self.hoverView subviews][0];
                NSMutableArray *words = [NSMutableArray arrayWithArray:[innerTextView.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                NSInteger wordCount = [words count];
                double noOfWordsPerSec = 3.33;//average readers are the majority and only reach around 200 wpm.
                double noOfSecsRequired = (ceil)(wordCount/noOfWordsPerSec);
                double bonusSecs = 1.0;
                
                [UIView animateWithDuration:1 delay:(noOfSecsRequired + bonusSecs) options:0
                                 animations:^{
                                     [self.hoverView setAlpha:0.0f];
                                 }
                                 completion:^(BOOL finished){
                                     if (finished)
                                         [self.hoverView removeFromSuperview];
                                 }];
            }
        }
    }
}

- (void)initialSetup {
    self.textContainer.maximumNumberOfLines = 1;
    self.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
    self.scrollEnabled = false;
    self.editable = FALSE;
    self.selectable = FALSE;
    [self setDataDetectorTypes:UIDataDetectorTypeAll];
    
    for (UIGestureRecognizer *recognizer in self.gestureRecognizers) {
        if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
            recognizer.enabled = NO;
        }
    }
    
    
    UILongPressGestureRecognizer *longPressGesRec = [[UILongPressGestureRecognizer alloc]
                                                     initWithTarget:self
                                                     action:@selector(onLongPress:)];
    [self addGestureRecognizer:longPressGesRec];
}

- (void)awakeFromNib {
    [super awakeFromNib];
}

@end

usage
CustomTextView *ctv = [[CustomTextView alloc] initWithFrame:CGRectMake(65, 300, 150, 30)];
ctv.text = @”replace this with a lengthy text…..”;
[self.view addSubview:ctv];

Please note the followings.

1. The width of the hover view is match with the with of the textview.
2. Depending on the available height, the Hover view will be appeared top or below of the textview.
3. The hover view will be automatically fade away after a certain amount of time – the displaying time will be calculated based on the number of words in the given text.

Thank you and happy coding… 🙂

Custom Hyperlink Control for iOS(Objective-C version)

Here comes the iOS version of the Custom Hyperlink Control. iOS also doesn’t come up with a native Hyperlink Control.

Implementation

#import <UIKit/UIKit.h>

@interface CustomHyperlink : UIControl<UITextViewDelegate>

NS_ASSUME_NONNULL_BEGIN

@property UITextView *innerText;
@property UIColor *defaultColor;
@property UIColor *pressedColor;
@property NSDictionary *hyperlinkAttribute;

@property (assign) SEL action;
@property (readonly, strong, nullable) id target;
@property (readonly, strong, nullable) id param;

- (void)setLinkText:(NSString*) valueIn;
- (NSString*)linkText;
- (void)addTarget:(nullable id)targetIn action:(SEL)actionIn param:(nullable id)paramIn;

NS_ASSUME_NONNULL_END

@end
#import "CustomHyperlink.h"

@implementation CustomHyperlink

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        CGRect parentFrame = self.frame;
        CGRect frame = CGRectMake(0, 0, parentFrame.size.width, parentFrame.size.height);
        [self setHyperlinkColors];
        [self setInnerTextCtrl:frame];
        [self addTarget:self action:@selector(executeOnTappedEvent:) forControlEvents:UIControlEventTouchDown];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setHyperlinkColors];
        [self setInnerTextCtrl:frame];
        [self addTarget:self action:@selector(executeOnTappedEvent:) forControlEvents:UIControlEventTouchDown];
    }
    return self;
}

- (void)addTarget:(nullable id)targetIn action:(SEL)actionIn param:(nullable id)paramIn{
    _target = targetIn;
    _action = actionIn;
    _param = paramIn;
}

- (void)setLinkText:(NSString*)valueIn
{
    [self setHyperlinkAttribute];
    self.innerText.attributedText = [[NSAttributedString alloc] initWithString:valueIn attributes:self.hyperlinkAttribute];
}

- (NSString*)linkText
{
    return self.innerText.text;
}

#pragma tapped event

- (void)executeOnTappedEvent:(UIView *)view
{
    UIColor *beforeColor = self.innerText.textColor;
    [UIView transitionWithView:view
                      duration:1
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        self.innerText.textColor = _pressedColor;
                    }
                    completion:^(BOOL finished){
                        if (finished) {
                            [self.target performSelector:self.action withObject:self.param afterDelay:0.1];
                            self.innerText.textColor = beforeColor;
                        }
                    }];
}

- (void)textViewDidChangeSelection:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
	CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
	CGRect newFrame = textView.frame;
	newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
	textView.frame = newFrame;
	
	CGRect selfFrame = self.frame;
	selfFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
	self.frame = selfFrame;
}

#pragma set methods

- (void)setInnerTextCtrl:(CGRect)frame
{
    self.innerText = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    [self.innerText setFont:[UIFont systemFontOfSize:14]];
    [self.innerText setAutocorrectionType:UITextAutocorrectionTypeNo];
    self.innerText.userInteractionEnabled = FALSE;
    self.innerText.scrollEnabled = FALSE;
    self.innerText.editable = FALSE;
    self.innerText.selectable = FALSE; // Add this property for ios 7 to disable the link type
    [self.innerText setDataDetectorTypes:UIDataDetectorTypeAll];
    self.innerText.delegate = self;
    [self.innerText setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    [self addSubview:self.innerText];
}

- (void)setHyperlinkColors
{
    self.defaultColor = [UIColor blackColor];
    self.pressedColor = [UIColor greenColor];
}

- (void)setHyperlinkAttribute
{
    self.hyperlinkAttribute = @{NSFontAttributeName:[UIFont systemFontOfSize:self.innerText.font.pointSize], NSForegroundColorAttributeName: _defaultColor, NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)};
}

@end

Typical Usage

CustomHyperlink *hyperlink = [[CustomHyperlink alloc] initWithFrame:CGRectMake(controlXPosition, currentYPosition, controlWidth, controlHeight)];
[hyperlink addTarget:self action:@selector(executeTapEvent:) param:hyperlink];
[self.scrollView addSubview:hyperlink];

Happy coding…. 🙂

Custom Hyperlink Control for Windows(Windows 8.1, Windows Phone 8.1)

Ended up building a user control which behaves similarly in both Windows and Windows Phone environments. With this you’ll get the underline effect, stating of default color as well as the press color.
Designer code


<UserControl x:Class="MyApp.Architecture.Controls.CustomHyperlink" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:MyApp.Architecture.Controls" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Background="YellowGreen">
    <HyperlinkButton x:Name="innerHyperlinkCtrl" FontFamily="Segoe WP Light">
        <HyperlinkButton.Content>
            <TextBlock FontFamily="Segoe UI" x:Name="inlineText">
					<Underline>
						<Run x:Name="ulRHlink"/>
					</Underline>
            </TextBlock>
        </HyperlinkButton.Content>
    </HyperlinkButton>
</UserControl>

C# code


public sealed partial class CustomHyperlink : UserControl
{
	private HyperlinkButton innerCtrl;
	private TextWrapping textWrapping = TextWrapping.WrapWholeWords;

	#region Constructors

	public CustomHyperlink()
	{
		this.InitializeComponent();
		this.Loaded += CustomHyperlink_Loaded;
		this.InnerCtrl = innerHyperlinkCtrl;

		this.DefaultColor = "#000000";
		this.PressedColor = "#40ff00";
	}

	#endregion

	#region Getters, Setters

	public HyperlinkButton InnerCtrl
	{
		get { return this.innerCtrl; }
		private set { this.innerCtrl = value; }
	}

	#endregion

	#region Events

	void CustomHyperlink_Loaded(object sender, RoutedEventArgs e)
	{
		this.InnerCtrl.Style = (this.Style == null) ? GetDefaultStyle() : this.Style;
		this.inlineText.TextWrapping = this.textWrapping;

		this.InnerCtrl.VerticalAlignment = this.VerticalAlignment;
		this.InnerCtrl.HorizontalAlignment = this.HorizontalAlignment;
		this.InnerCtrl.FontSize = this.FontSize;
		this.InnerCtrl.FontWeight = this.FontWeight;
		this.InnerCtrl.Margin = this.Margin;
	}

	#endregion

	#region Dependency Properties

	public static readonly DependencyProperty LinkTextProperty = DependencyProperty.Register("LinkText", typeof(string), typeof(CustomHyperlink), new PropertyMetadata(null, new PropertyChangedCallback(OnContentChanged)));
	public string LinkText
	{
		get { return (string)GetValue(LinkTextProperty); }
		set { SetValue(LinkTextProperty, value); }
	}

	private static void OnContentChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
	{
		CustomHyperlink mhl = sender as CustomHyperlink;
		mhl.ulRHlink.Text = (e.NewValue != null) ? e.NewValue.ToString() : string.Empty;
	}

	public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register("TextWrapping", typeof(TextWrapping), typeof(CustomHyperlink), null);
	public TextWrapping TextWrapping
	{
		get { return (TextWrapping)GetValue(TextWrappingProperty); }
		set 
		{ 
			SetValue(TextWrappingProperty, value);
			this.inlineText.TextWrapping = value;
		}
	}

	public static readonly DependencyProperty DefaultColorProperty = DependencyProperty.Register("DefaultColor", typeof(string), typeof(CustomHyperlink), null);
	public string DefaultColor
	{
		get { return (string)GetValue(DefaultColorProperty); }
		set { SetValue(DefaultColorProperty, value); }
	}

	public static readonly DependencyProperty PressedColorColorProperty = DependencyProperty.Register("PressedColor", typeof(string), typeof(CustomHyperlink), null);
	public string PressedColor
	{
		get { return (string)GetValue(PressedColorColorProperty); }
		set { SetValue(PressedColorColorProperty, value); }
	}

	public static readonly DependencyProperty NavigateUriProperty = DependencyProperty.Register("NavigateUri", typeof(Uri), typeof(CustomHyperlink), null);
	public Uri NavigateUri
	{
		get { return (Uri)GetValue(NavigateUriProperty); }
		set 
		{ 
			SetValue(NavigateUriProperty, value); 
			this.InnerCtrl.NavigateUri = value; 
		}
	}

	#endregion

	#region Default Style

	private Style GetDefaultStyle()
	{
		StringBuilder styleBuilder = new StringBuilder();
		styleBuilder.Append("<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" 
                      xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" x:Key=\"CustomHyperlinkButtonStyle\" TargetType=\"HyperlinkButton\">");           
			styleBuilder.Append("<Setter Property=\"Template\">");
				styleBuilder.Append("<Setter.Value>");
					styleBuilder.Append("<ControlTemplate TargetType=\"HyperlinkButton\">");
						styleBuilder.Append("<Grid>");
						styleBuilder.Append("<VisualStateManager.VisualStateGroups>");
							styleBuilder.Append("<VisualStateGroup x:Name=\"CommonStates\">");
								styleBuilder.Append("<VisualState x:Name=\"Normal\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBNormal\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"" + DefaultColor + "\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
								styleBuilder.Append("<VisualState x:Name=\"Pressed\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBPressed\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"" + PressedColor + "\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
								styleBuilder.Append("<VisualState x:Name=\"Disabled\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBDisabled\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"{ThemeResource HyperlinkDisabledThemeBrush}\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
							styleBuilder.Append("</VisualStateGroup>");
						styleBuilder.Append("</VisualStateManager.VisualStateGroups>");
						styleBuilder.Append("<ContentPresenter x:Name=\"ContentPresenter\" AutomationProperties.AccessibilityView=\"Raw\" ContentTemplate=\"{TemplateBinding ContentTemplate}\" ContentTransitions=\"{TemplateBinding ContentTransitions}\" Content=\"{TemplateBinding Content}\" HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\">");
						styleBuilder.Append("</ContentPresenter>");
						styleBuilder.Append("</Grid>");
					styleBuilder.Append("</ControlTemplate>");
				styleBuilder.Append("</Setter.Value>");
			styleBuilder.Append("</Setter>");
		styleBuilder.Append("</Style>");

		return (Style)XamlReader.Load(styleBuilder.ToString());
	}

	#endregion
}

Typical Usage (XAML)


<custctrl:CustomHyperlink x:Name="GoogleLink" HorizontalAlignment="Stretch" VerticalAlignment="Center" FontSize="14" Margin="0,20,0,0" NavigateUri="www.google.com" LinkText="Link to Google"/>

Typical Usage(C# class)


CustomHyperlink customHyperlink = new CustomHyperlink();
customHyperlink.Name = standardControlName;
customHyperlink.DefaultColor = "#000000";
customHyperlink.PressedColor = "#40ff00";
customHyperlink.HorizontalAlignment = HorizontalAlignment.Left;
customHyperlink.VerticalAlignment = VerticalAlignment.Center;
customHyperlink.LinkText = "Hello There";

Happy coding…. 🙂

Custom Hyperlink Control for Android

I developed a custom control to mimic the Hyperlink behavior as Android doesn’t have a built-in/native Hyperlink Control.

Implementation

public class CustomHyperlink extends TextView {

    private int mDefaultColor = Color.BLACK;
    private int mPressedColor = Color.GREEN;

    //region #Constructors

    public CustomHyperlink(Context context) {
        super(context);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)
                    setTextColor(mPressedColor);
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_OUTSIDE
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    setTextColor(mDefaultColor);
                }
                return false;
            }
        });
    }

    public CustomHyperlink(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomAttrValues(context, attrs);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)
                    setTextColor(mPressedColor);
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_OUTSIDE
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    setTextColor(mDefaultColor);
                }
                return false;
            }
        });
    }

    public CustomHyperlink(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomAttrValues(context, attrs);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)
                    setTextColor(mPressedColor);
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_OUTSIDE
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    setTextColor(mDefaultColor);
                }
                return false;
            }
        });
    }

    //endregion

    //region #Getters, Setters

    public int getDefaultColor() {
        return mDefaultColor;
    }

    public void setDefaultColor(int defaultColor) {
        this.mDefaultColor = defaultColor;
    }

    public int getPressedColor() {
        return mPressedColor;
    }

    public void setPressedColor(int pressedColor) {
        this.mPressedColor = pressedColor;
    }

    //endregion

    //region #Methods

    public void setLinkText(String value) {
        if (MetrixStringHelper.isNullOrEmpty(value)) return;

        SpannableString content = new SpannableString(value);
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        setText(content);

        setTextColor(mDefaultColor);j
    }

    public void setLinkText(String value, int start, int end) throws Exception {
        if (MetrixStringHelper.isNullOrEmpty(value)) return;

        if (end > value.length())
            throw new Exception(AndroidResourceHelper.getMessage("EndValIsGreaterThan"));

        SpannableString content = new SpannableString(value);
        content.setSpan(new UnderlineSpan(), start, end, 0);
        setText(content);

        setTextColor(mDefaultColor);
    }

    public String getLinkText() {
        return this.getText().toString();
    }

    private void setCustomAttrValues(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomHyperlinkAttr);
		if (typedArray != null) {
			//region #setLinkText
			String s = typedArray.getString(R.styleable.CustomHyperlinkAttr_linkText);
			if (!MetrixStringHelper.isNullOrEmpty(s))
				setLinkText(s);
			//endregion
		}
    }

    //endregion
}

I hope you have some basic understanding about the android custom attributes. You can declare your own attributes in a xml file such as attrs.xml and it can be placed inside res\values\ folder.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomHyperlinkAttr">
        <attr name="linkText" format="string"></attr>
    </declare-styleable>
</resources>

Usage (Inside a XML layout)


<com.architecture.utilities.MetrixHyperlink
ndroid:id="@+id/web_url"
attr:linkText="www.abc.com"
android:gravity="center_horizontal"/>

Don’t forget to add the following line into the top most layout.
xmlns:attr=”http://schemas.android.com/apk/res-auto&#8221;

Ex:


<?xml version="1.0" encoding="utf-8"?> <LinearLayout style="@style/LinearBase.Normal.Vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns="http://schemas.android.com/tools"
xmlns:attr="http://schemas.android.com/apk/res-auto">

Usage (Inside a Class)


CustomHyperlink webUrlHyperLink = (CustomHyperlink) findViewById(R.id.web_url);
webUrlHyperLink.setLinkText("www.xyz.com");

Happy coding…. 🙂

Forcing newly entered characters to be in UPPERCASE in a TextBox

For Windows Store Apps(Windows 8.1 & Windows Phone 8.1)


///
<summary>
/// Identify whether the pressed key is a Letter(Ex: a, B..)
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
	int keyValue = (int)e.Key;
	if (keyValue >= 0x41 && keyValue <= 0x5A)
		isLetter = true;
}

///
<summary>
/// Identify whether a text PASTE is happened.
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_Paste(object sender, TextControlPasteEventArgs e)
{
	var textBox = sender as TextBox;
	startingLocation = textBox.SelectionStart;
	pasteOccurred = true;
}

///
<summary>
/// Change the newly entered character's case to upper case / a set of characters (Ex: text Paste)
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
	var textBox = sender as TextBox;
	var newText = textBox.Text;
	int currentPosition = textBox.SelectionStart;

	#region text paste

	if (pasteOccurred)
	{
		string newCharacters = newText.Substring(startingLocation, (currentPosition-startingLocation));
		newText = newText.Remove(startingLocation, newCharacters.Length).Insert(startingLocation, newCharacters.ToUpper());
		textBox.Text = newText;
		textBox.SelectionStart = currentPosition;

		pasteOccurred = false;
		startingLocation = -1;

		return;
	}

	#endregion

	if (!isLetter) return;

	currentPosition = textBox.SelectionStart - 1;
	if (currentPosition < 0) return; 	if (Char.IsLower(newText, currentPosition)) 	{ 		string newCharacter = newText.Substring(currentPosition, 1); 		newText = newText.Remove(currentPosition, 1).Insert(currentPosition, newCharacter.ToUpper()); 		textBox.Text = newText; 		textBox.SelectionStart = currentPosition + 1; 	} 	isLetter = false; } 

For Android(TextWatcher implementation)

 final EditText editText = (EditText) view; //new region force -> uppercase implementation
final TextWatcher textWatcher = new TextWatcher() {
	boolean shouldContinue = true;

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		//To avoid executing of text change listener -> onTextChanged when the time of data binding..
		shouldContinue = editText.hasFocus() ? true : false;
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if(!shouldContinue)return;

		int curCursorLoc = editText.getSelectionEnd();
		if(curCursorLoc < 1) return;

		CharSequence charSet = s.subSequence(start, (start + count));
		if(charSet != null) {
			String upperStr = charSet.toString().toUpperCase();
			StringBuilder stringBuilder = new StringBuilder(s);
			stringBuilder.replace(start, (start + count), upperStr);
			editText.setText(stringBuilder.toString());
			editText.setSelection(curCursorLoc);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
	}
};

editText.addTextChangedListener(textWatcher);
//endregion

For iOS (iPhone or iPad)


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    BOOL shouldChange;
    NSRange lowercaseCharRange;
	lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];

	if (lowercaseCharRange.location != NSNotFound) {
		textField.text = [textField.text stringByReplacingCharactersInRange:range
																 withString:[string uppercaseString]];
		UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument inDirection:UITextLayoutDirectionRight offset:(range.location + 1)];
		UITextRange *newCursorRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
		[textField setSelectedTextRange:newCursorRange];
		shouldChange = NO;
	}
	else
		shouldChange = YES;

    return shouldChange;
}

Run two instances of the same application in Mac OS

Recently I came across a situation where I needed to run two instances of XCode application to compare two different versions of the project that I’m working.

Once a XCode application is opened and if you want to bring up another instance, you can’t do it by simply tapping on the XCode icon in the shortcut bar/via Applications folder.

You have to execute the following simple command using the Terminal.

open -n /Applications/Xcode.app

 

Dealing with EMFILE(Too many open files) & OOM(OutOfMemory) Exceptions in Android

Today I’m going to write about some of the issues I faced while developing an Image Gallery with caching techniques, efficient bitmap loading and what tactics that I’ve taken to overcome the issues.

I have developed a custom image gallery with the use of android GridView. Key requirement was to load large amount of images with limited time. In addition the user should be able to smoothly scroll up-down the gallery control.

In order to accomplish this, I have used caching techniques like LruCache, scale down the images before loading (low memory consumption) and loading the images asynchronously (with the use of AsyncTask).

I experienced the above mentioned EMFILE(Too many open files) exception while I was testing this. At this time there were 50-100 images were loaded into the Image Gallery and I was scrolling up and down for around 10-20 times.

EMFILE(Too many open files)

This was happening due a limitation in Android(We can say this is an inherited behavior of Linux). The reason behind this is Android limits the max open files per process to 1024. So this can be experienced in a scenario like Image Gallery with large amount of files, unless we carefully handle the file processing techniques.

But finally got a clue.

It was the process of scaling down the images. It had few FileInputStream objects which were not closed after consuming.

protected static Bitmap decodeFile(File imageFile, int requiredHeight, int requiredWidth) throws Exception {

	// Decode image size
	BitmapFactory.Options oSize = new BitmapFactory.Options();

	oSize.inJustDecodeBounds = true;
	oSize.inDither = false;
	oSize.inPurgeable = true;
	oSize.inInputShareable = true;

	//FileInputStream is used, but it's not closing after consuming...
	BitmapFactory.decodeStream(new FileInputStream(imageFile), null, oSize);

	// Find the correct scale value. It should be the power of 2.
	int width_tmp = oSize.outWidth, height_tmp = oSize.outHeight;
	int scale = 1;
	while (true) {
		if (width_tmp <= requiredWidth || height_tmp <= requiredHeight)
			break;
		width_tmp /= scale;
		height_tmp /= scale;
		scale *= 2;
	}

	// Decode with inSampleSize
	BitmapFactory.Options oPreview = new BitmapFactory.Options();
	oPreview.inSampleSize = scale;
	oPreview.inDither = false;
	oPreview.inPurgeable = true;
	oPreview.inJustDecodeBounds = false;
	oPreview.inInputShareable = true;

	//FileInputStream is used, but it's not closing after consuming...
	return BitmapFactory.decodeStream(new FileInputStream(imageFile), null, oPreview);

}

Following is the modified version of the code block, and I was able to get rid of EMFILE(Too many open files) exception.


protected static Bitmap decodeFile(File imageFile, int requiredHeight, int requiredWidth) throws Exception {

	FileInputStream fileInputStreamIn = null;
	FileInputStream fileInputStreamOut = null;
	
	try{
		// Decode image size
		BitmapFactory.Options oSize = new BitmapFactory.Options();
		
		oSize.inJustDecodeBounds = true;
		oSize.inDither = false;
		oSize.inPurgeable = true;
		oSize.inInputShareable = true;
		
		fileInputStreamIn = new FileInputStream(imageFile);
		BitmapFactory.decodeStream(fileInputStreamIn, null, oSize);

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = oSize.outWidth, height_tmp = oSize.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp <= requiredWidth || height_tmp <= requiredHeight)
				break;
			width_tmp /= scale;
			height_tmp /= scale;
			scale *= 2;
		}

		// Decode with inSampleSize
		BitmapFactory.Options oPreview = new BitmapFactory.Options();
		oPreview.inSampleSize = scale;
		oPreview.inDither = false;
		oPreview.inPurgeable = true;
		oPreview.inJustDecodeBounds = false;
		oPreview.inInputShareable = true;
		
		fileInputStreamOut = new FileInputStream(imageFile);
		return BitmapFactory.decodeStream(fileInputStreamOut, null, oPreview);
	}
	finally{
		//Got rid of EMFILE Exception(Too many file open)
		if(fileInputStreamIn != null)
			fileInputStreamIn.close();
		if(fileInputStreamOut != null)
			fileInputStreamOut.close();
	}

}

OOM(OutOfMemory)

The application got crashed, soon after I left the screen which had the Image Gallery. This was due to OOM Exception. This issue was also bit tricky, since there was no straight forward way of identifying the reason behind this. The Image Gallery (Custom GridView) Adapter was fully enhanced to reuse the views (using of ViewHolder pattern which Android has suggested), so I thought this wasn’t causing the error. Then my eyes turned into the implementation of LruCache. There was a slight mistake in LruCache, because when the time of initializing it I have used a fixed size for it.

So, DON’T DO THIS,


mMemoryCache = new LruCache<String, Bitmap>(30)

because what Android has suggested is, set the size of LruCache dynamically depending of the available memory.


final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

final int cacheSize = maxMemory / 8;

mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
	@Override
	protected int sizeOf(String key, Bitmap bitmap) {
		return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
	}
};

With the help of above modification, I was able to get rid of the OOM Exception.

Happy Coding…. 🙂

Creating a workable Android 5.0 (Lollipop) Emulator

At the beginning I was struggling while setup and running a Android Lollipop emulator. So I thought putting all the steps into one place and sharing it in a simpler manner.

This was fully tested in Windows 7 (64 bit) environment with Eclipse JUNO Version: 4.2.1.

1. Please make sure that you have the latest Android SDK Tools and Android SDK Platform-tools. If not please update them to the latest version.

2

2. Install necessary components of Android 5.0(API21). For the moment, I didn’t install the components related to Android TV.

4

3. Make sure that you have installed Android SDK Build-tools -> Rev. 21.

3

3. Make sure that you have the latest component of Android Support Library & Google Play services.

5

4. You must install Intel x86 Emulator Accelerator(HAXM installer). Don’t use the Android SDK Manager for installing that.

6

Because at the moment the SDK Manager gives you HAMX installer version 1.1.0. But to build up Android Lollipop emulator, it requires the latest version of HAMX which is 1.1.1. This can be found in the following link Intel x86 Emulator Accelerator(HAMX installer)

5. Next go and build the Android Lollipop emulator.

6. I have selected Nexus 5 as the device.

11

7. When you are creating the Android Lollipop emulator(AVD) make sure to select Android 5.0-API Level 21 as the Target.

7

If you select Google APIs – API Level 21, you might get a warning even if you have installed Google APIs Intel Atom(x86) system image.

Warning

8. For CPU/ABI, I have chosen Google APIs Intel Atom(x86_64).

8

9. Make sure that you have selected Use Host GPU option rather than Snapshot in Emulation Options. Otherwise when the emulator starts you will see nothing but a black blank screen only.

9

Finally you are ready to go. Start your newly created Android Lollipop emulator(AVD) from the AVD list.

12