Facebook Native Ads not showing, error "1011 - Display Format Mismatch" - facebook-android-sdk

I want to implement the Facebook Audience Network "Native Ads" and display them in a RecyclerView at every Nth position in the list.
I already got the regular banners running in the same app and have no problems there. However, the native ads don't load and I just get a blank rectangle with no content.
When I check the logfile I can see that I keep ending up in "onError" of nativeAd.setAdListener(new NativeAdListener())... getting this error message:
The display format in the ad request does not match the display
format specified for this placement. Each placement can only be used
with a single display format. You can create multiple placements in
order to use multiple display formats.
My layout XML looks like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/outer_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/blue"
android:orientation="vertical"
android:padding="#dimen/outer_padding_listview_item">
<com.facebook.ads.NativeAdLayout
android:id="#+id/native_ad_container"
android:layout_width="250dp"
android:layout_height="280dp"
android:layout_gravity="center"
android:background="#color/white"
android:orientation="vertical" />
FacebookNativeAdListViewItemHolder.java
public class FacebookNativeAdListViewItemHolder extends RecyclerView.ViewHolder {
private static final String TAG = FacebookNativeAdListViewItemHolder.class.getSimpleName();
private final NativeAd nativeAd;
public View view;
private Context context;
#BindView(R.id.outer_layout)
LinearLayout outerLayout;
#BindView(R.id.native_ad_container)
NativeAdLayout nativeAdContainer;
public FacebookNativeAdListViewItemHolder(View view, Context context) {
super(view);
ButterKnife.bind(this, view);
this.view = view;
this.context = context;
nativeAd = new NativeAd(context, Konstanten.FACEBOOK_AUDIENCE_NETWORK_NATIVE_AD_IN_RECYCLER_VIEW);
nativeAd.setAdListener(new NativeAdListener() {
#Override
public void onError(Ad ad, AdError adError) {
Log.d(TAG, "onError(): " + adError.getErrorMessage());
}
#Override
public void onAdLoaded(Ad ad) {
Log.d(TAG, "FacebookNativeAdListViewItemHolder onAdLoaded()");
// Render the Native Ad Template
View adView = NativeAdView.render(context, nativeAd);
// Add the Native Ad View to your ad container.
// The recommended dimensions for the ad container are:
// Width: 280dp - 500dp
// Height: 250dp - 500dp
// The template, however, will adapt to the supplied dimensions.
nativeAdContainer.addView(adView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 800));
}
#Override
public void onAdClicked(Ad ad) {
Log.d(TAG, "FacebookNativeAdListViewItemHolder onAdClicked()");
}
#Override
public void onLoggingImpression(Ad ad) {
Log.d(TAG, "FacebookNativeAdListViewItemHolder onLoggingImpression()");
}
#Override
public void onMediaDownloaded(Ad ad) {
Log.d(TAG, "FacebookNativeAdListViewItemHolder onMediaDownloaded()");
}
});
// Initiate a request to load an ad.
nativeAd.loadAd();
}
}
It all builds fine and I can see the rectangle in the recyclerview where the native ad should be displayed. But the problem is that it just remains white and there's no content displayed (see screenshot).

You need to add a testing device to show ads
Go to your Monetization Manager from navigation menu select Integration --> Testing
Enable Testing and check on 'Use real advertiser content'
Now add your testing device by adding 'Google Advertiser Id' from your 'Settings->Google Account->Ads'
Click here for more information

Eventually I was able to find the problem. The problem was the wrong ad format (rectangle instead of natvie-ad) and therefore wasn't able to display an ad in a native ad container.

Related

Getting Profile Photo from Microsoft Graph API for Android

I have recently started working on an android project that uses Microsft authentication and graph API. By following this:
https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-android
I am able to authenticate and get some data from graph API. Now I want to load the profile photo of Microsoft account in the app. For this purpose, I used ProfilePhoto object with a call back as follows:
graphClient
.me()
.photo()
.buildRequest()
.get(new ICallback<ProfilePhoto>() {
#Override
public void success(ProfilePhoto profilePhoto) {
Log.d(TAG, "Found " + profilePhoto.getRawObject().toString());
}
#Override
public void failure(ClientException ex) {
displayError(ex);
}
});
Here profilePhoto.getRawObject() returns a json file like:
{"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users('hanzla_hawk%40outlook.com')/photo/$entity","#odata.mediaContentType":"image/png","#odata.mediaEtag":"W/\"8050a078da935403cf67163f23f1baace5c7abf3ff784452cb08c38660308a83\"","id":"default","height":256,"width":256}
With this Json, how can I load the image into an image view? I have previous experience with Picasso and other fake apis. But right now I just dont know what should I pass in the Picasso to load image from this json.
I have just make a call to get a profile photo to show on an Android app using Jetpack Compose views in Kotlin. To achieve it I have followed your question and this tutorial:
https://learn.microsoft.com/en-us/graph/tutorials/android
You almost got it. Just add .content() call between .me().photo() and .buildRequest().
This is my code on my project to get the photo content:
// GET /me/photo/$value (logged in user)
fun getUserPhoto(
onGotPhoto: (ImageBitmap) -> Unit,
onGotError: (Exception) -> Unit
) {
mClient!!.me().photo().content().buildRequest()
.async
.thenAccept { inputStream ->
val bitmap = BitmapFactory.decodeStream(inputStream).asImageBitmap()
onGotPhoto.invoke(bitmap)
}
.exceptionally { processError(it, onGotError) }
}

Wicket Deployment mode map resources wrong way

I have Page
getRootRequestMapperAsCompound().add(new NoVersionMapper("/card/${cardId}", CardPage.class));.
On this page there is TinyMCE4 editor. Which try to load images using relative path "images/1.jpg"
I've added resource mapping to allow images successfuly loaded.
mountResource("/card/image/${imageId}", imageResourceReference);
In DEVELOPMENT mode everything work nice, image are loaded in to editor, but in DEPLOYMENT mode, Page has been called twice, first time for /card/1 and second time for /card/image/1.jpg.
How to correctly mount resources for DEPLOYMENT mode?
UPDATE look like found the reason
public int getCompatibilityScore(Request request)
{
return 0; // pages always have priority over resources
}
, but then the question is: "Why it is working nice in development mode"?
Update 2 I haven't find better solution then add my own Resource Mapper with overrided getCompatibilityScore()
public class ImageResourceMapper extends ResourceMapper {
private String[] mountSegments;
public ImageResourceMapper(String path, ResourceReference resourceReference) {
super(path, resourceReference);
mountSegments = getMountSegments(path);
}
public ImageResourceMapper(String path, ResourceReference resourceReference, IPageParametersEncoder encoder) {
super(path, resourceReference, encoder);
mountSegments = getMountSegments(path);
}
#Override
public int getCompatibilityScore(Request request) {
if (urlStartsWith(request.getUrl(), mountSegments)) {
return 10;
}
return 0;
}
}

Xamarin Forms Dynamically Load Content in a Page

My current set up:
Xamarin Forms, consisting of iOS, Android, WP app and shared PCL.
Using MVVM Light to keep a nice separation of concerns.
Brief intro into what I want to achieve. I want to have a Base page that has a Cancel and Next button. On pressing the Next button Content is loaded dynamically within that base page.
Xaml View:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="LogInPresenterView">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Cancel" Priority="0" Order="Primary" Command="{Binding Cancel}"></ToolbarItem>
<ToolbarItem Text="Next" Priority="1" Order="Primary" Command="{Binding Next}"></ToolbarItem>
</ContentPage.ToolbarItems>
</ContentPage>
ViewModel Code:
public class LogInPresenterViewModel : ViewModelBase
{
public LogInPresenterViewModel() {}
private RelayCommand _next;
public RelayCommand Next
{
get
{
return _next ?? (_next = new RelayCommand(async () => await DoNext()));
}
}
private async Task DoNext()
{
// IN HERE I WOULD LIKE TO DYNCAMICALLY LOAD CONTENT / VIEWS
}
}
Usually you would have a StackLayout etc before the element. However, on clicking the Next Toolbar Item I want to dynamically load content (that has a viewmodel).
So maybe my ICommand for my next button checked to see what the current content type was, and depending on that I would load another bit of content.
The scenario would be, the base page would load along with the first bit of content - Enter Email and Password. User enters that then clicks on next, if all ok, the content is replaced with the option to enter a security code, keeping the base Close and Next buttons at the top.
Hopefully this makes sense. I know what I want to do in my head, I just don't know how to translate that into Xamarin Forms...
Ok,
So first job is to create your region service in your PCL. This will look something like this:
using System;
using System.Collections.Generic;
namespace xxx
{
public class RegionService : IRegionService
{
private Dictionary<string, object> _regionDictionary;
public RegionService ()
{
_regionDictionary = new Dictionary<string, object> ();
}
#region IRegionService implementation
public bool RegisterRegion (string regionName, object regionObject)
{
object region = null;
_regionDictionary.TryGetValue (regionName, out region);
if (region != null)
_regionDictionary [regionName] = regionObject;
else
_regionDictionary.Add (regionName, regionObject);
return true;
}
public object ResolveRegion (string regionName)
{
object region = null;
_regionDictionary.TryGetValue (regionName, out region);
if (region == null)
throw new RegionServiceException ("Unable to resolve region with given name");
return region;
}
#endregion
}
}
This when you create your page with the dynamic content register your dynamic contentview in your code behind:
ContentView contentView = this.FindById<ContentView>("myContentView");
regionService.RegisterRegion("DynamicView", contentView);
You'll need to create an interface for your views and pages to use to indicate which region they wish to be presented in:
using System;
namespace xxx
{
public interface IRegionView
{
string GetRegionName ();
}
}
Then in your code behind for your view implement this interface to return the name of the region to display in.
You now need a custom presenter to use this region code. I use MVVMCross, so the details will vary for the MVVM implementation you are using, but essentially something like this is what you need:
public async static Task PresentPage(Page page)
{
if (typeof(IRegionView).GetTypeInfo().IsAssignableFrom(page.GetType().GetTypeInfo()))
{
IRegionService regionService = Mvx.Resolve<IRegionService>();
string regionName = (page as IRegionView).GetRegionName();
Page region = regionService.ResolveRegion(regionName) as Page;
if (typeof(IModalPage).GetTypeInfo().IsAssignableFrom(page.GetType().GetTypeInfo()))
await region.Navigation.PushModalAsync(page);
else if (typeof(IPopupPage).GetTypeInfo().IsAssignableFrom(page.GetType().GetTypeInfo()))
region.PushOverlayPage(page);
else if (typeof(NavigationPage).GetTypeInfo().IsAssignableFrom(region.GetType().GetTypeInfo()))
await (region as NavigationPage).PushAsync(page);
}
}
I hope this is useful for you :)
So if this was me. I would create a region service where the contentview registers a unique region name.
Content would then be marked to use that region, and a custom presenter can be used to show the view model's content in the appropriate region.
I'm on my phone whilst travelling at the moment but I can post some code later on if that helps :)
Tristan
You can dynamically load Xamarin Forms UI with XAML.
Old Answer:
This can be achieved with the use of the LoadFromXaml method. It works in the same was as XamlReader.Load in Silverlight/WPF. It is a hidden method that can be only accessed through reflection. There is an article on how to do it here:
http://www.cazzulino.com/dynamic-forms.html
But, I would like to ask to you go to this feature request at Xamarin and ask that the method be made public so that it becomes a fully supported feature:
https://forums.xamarin.com/discussion/comment/252626

Overwrite the LoginWidget and Set DestinationPageUrl dynamically in Sitefinity

I want to add some custom code during the login function, in particular i want to redirect the user after login to the previous page.
For example: i'm on page A , i want to download something from this page, but i'm not authorized. Then pops a popup with link to the login page. After successful login i'm back on page A.
For this purpose i want to overwrite the LoginWidged and to set value to"this.DestinationPageUrl" dynamically.
I read about similar issues here and here, but there isn't an example how to overwrite this LoginWidget class.
I create CustomLoginControl.cs file in my project and register as a new custom control, but after rendering it on the page, it didn't work. Login button does not make nothing. I'm not sure what exactly have to do and which of methods have to overwrite.
namespace SitefinityWebApp.UserControls
{
public class CustomLoginControl : Telerik.Sitefinity.Web.UI.PublicControls.LoginWidget
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
this.DestinationPageUrl = "http://previousPage.com";
base.Render(writer);
}
}
}
Can you give me an example how to overwrite this class to work properly.
Version: Sitefinity 5.0, Claims-based authentication
I've done something similar but instead of overriding the login control you can subscribe and capture the UnauthorizedAccess event, send the user to your login page with your redirect page as a query string parameter. You'll need to add a Global.asax / Global.asax.cs file to your project, then add this to the Application_Start function:
protected void Application_Start(object sender, EventArgs e)
{
Bootstrapper.Initialized += BootstrapperInitialized;
}
Then add these two functions:
private void BootstrapperInitialized(object sender, ExecutedEventArgs e)
{
if (e.CommandName == "Bootstrapped")
{
EventHub.Subscribe<IUnauthorizedPageAccessEvent>(OnUnauthorizedAccess);
}
}
private void OnUnauthorizedAccess(IUnauthorizedPageAccessEvent unauthorizedEvent)
{
var manager = ConfigManager.GetManager();
string loginPage = manager.GetSection<ProjectConfig>().DefaultSite.FrontEndLoginPageUrl;
var redirectParam = unauthorizedEvent.RedirectUrl.Replace(string.Format("{0}?ReturnUrl=", loginPage), string.Empty);
var escaped = Uri.EscapeDataString(redirectParam);
unauthorizedEvent.HttpContext.Response.Redirect(string.Format("{0}?ReturnUrl={1}", loginPage, escaped));
}
You will also need to set your default front end login page in the settings under Administration -> Settings -> Advanced -> Project -> DefaultSite and the FrontEndLoginPageUrl setting.
This works for me on a 6.3 site, not sure if this is available in Sitefinity 5 or not.

MVVM Light Toolkit design approach (Navigation & view load)

I am building a simple application with 4-5 views in Silverlight. I came across MVVM Light toolkit and I think it suits my need.
Background
Application will have views with typical list and details display
Manufacturer
Product
and so on with left navigation, header and footer (User controls).
I am thinking of having a main page with user controls created at design time.
Problem
On selection of links from left navigation control, the central panel should be updated with a different view (like Manufacturer, product and so on)
I understand that Messenger is an option to communicate between different VMs in light toolkit.
Question
How can I design my app with MVVM light toolkit. Central pane need to be loaded with a different view at runtime.
I am particularly looking at help in implementing the navigation portion of the application.
Thank you.
I had to implement basic nagivigtion in an NON mvvm way. I have a message listener sitting on the constructor of my main view that listens for a page navigation message(custom message learn it, love it,use it)then it sets the content source of the nav frame to the url that is sent in the message. I have the URLs for all my page and subpage navigation setup using string constants.
public MainPage()
{
InitializeComponent();
Loaded += OnLoaded;
WebContext.Current.Authentication.LoggedOut +=
new EventHandler<System.ServiceModel.DomainServices.Client.ApplicationServices.AuthenticationEventArgs>(Authentication_LoggedOut);
Messenger.Default.Register<msgs.NavigationRequest<PageURI>>(this, (uri => ContentFrame.Navigate(uri.Content)));
Messenger.Default.Register<WavelengthIS.Core.Messaging.ExceptionMessage>(this, ex => ShowExceptionMessage(ex));
Messenger.Default.Register<WavelengthIS.Core.Messaging.StringMessage>(this, str => ShowMessageForUser(str));
}
public class PageURI : Uri
{
public PageURI(string uriString, UriKind uriKind)
: base(uriString, uriKind)
{
}
}
public class PageLinks
{
public const string SEARCHBYDAYCOUNTVIEW = "/Views/PatientSearchHeaders/SearchByDayCountView.xaml";
public const string SEARCHBYPATIENTCRITERIAVIEW = "/Views/PatientSearchHeaders/SearchByPatientCriteriaView.xaml";
public const string QUESTIONAIRRESHELL = "/Views/QuestionairreViews/QuestionairreShell.xaml";
public const string HOME = "/Views/PrimarySearchView.xaml";
public const string REPORTS = "/Views/ReportsPage.xaml";
public const string LOGINPAGE = "/Views/LoginPageView.xaml";
}
Actual Calling in VM:
private void OnSurveyCommandExecute()
{
Wait.Begin("Loading Patient List...");
_messenger.Send<ReadmitPatientListViewModel>(this);
_messenger.Send<Messages.NavigationRequest<SubClasses.URI.PageURI>>(GetNavRequest_QUESTIONAIRRESHELL());
}
private static Messages.NavigationRequest<SubClasses.URI.PageURI> GetNavRequest_QUESTIONAIRRESHELL()
{
Messages.NavigationRequest<SubClasses.URI.PageURI> navRequest =
new Messages.NavigationRequest<SubClasses.URI.PageURI>(
new SubClasses.URI.PageURI(Helpers.PageLinks.QUESTIONAIRRESHELL, System.UriKind.Relative));
return navRequest;
}