0
votes

I am trying to get the user agent calling the apex page header in an apex class through a trigger, to update a field depending on the user device (mobile or not).

Here's the code I'm using:

public static boolean isMobileDevice() {
    String userAgent = ApexPages.currentPage().getHeaders().get('User-Agent');
    if (userAgent == null) {
        return false;
    }
    Pattern p = Pattern.compile('Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune');
    Matcher pm = p.matcher(userAgent);
    return pm.find();        
}

When the trigger runs, it returns this error:

System.NullPointerException: Attempt to de-reference a null object: Class.MyClass.isMobileDevice: line 129, column 1

The 129th line is this one :

String userAgent = ApexPages.currentPage().getHeaders().get('User-Agent');

Is there a workaround to get the user agent from a controller in an apex trigger or is it just impossible ?

Thanks in advance for any help you are able to provide.

1

1 Answers

0
votes

I managed to do it finally.

I used a custom field on the object, and complete its value on creation of the record depending on user agent. Then in the trigger I only need to check that field and not the userAgent anymore.

Hope this can help.