Integration MoPub encounted un error and the pub not show: webcore can't get the viewwidth after the first layout - mopub

I recently integrate MoPub for showing the advertisement of my enterprise.
So I have added a part of xml into my main.xml
<com.mopub.mobileads.MoPubView
android:id="#+id/adview"
android:layout_width="fill_parent"
android:layout_height="50dp" />
And for download image of advertisement,
private static class LoadHtmlAdTaskResult extends LoadUrlTaskResult {
protected String mData;
private LoadHtmlAdTaskResult(AdView adView, String data) {
super(adView);
mData = data;
}
public void execute() {
if (mData == null)
return;
AdView adView = mWeakAdView.get();
if (adView == null || adView.isDestroyed())
return;
adView.mResponseString = mData;
Log.i(TAG, "LoadHtmlAdTaskResult");
//String contain html tags with images
String source =
"<img src='http://banner.testadvertisement.com/campaign/12563254'>";
adView.loadDataWithBaseURL("http://www.adserverpub.com",
source,"text/html","UTF-8","about:blank");
}
But The image doesn't show up and I always get this error in my catlog
"can't get the viewwidth after the first layout".
Does anyone have encountered this problem?
I have no idea where this error come from? Thank you all.

Related

Image not displaying in .NET MAUI Mac Catalyst

I'm trying to display an image to make my own custom splash screen using .NET MAUI. It is made in C# and does not use XAML. Here is my code:
SplashScreenActivity.cs:
using System;
using System.Text;
namespace LiveEditorHTML
{
public partial class SplashScreenActivity : ContentPage
{
Image splashScreenImage;
public async Task<string> ShowMsg(string title,
string msg, bool isQuestion, bool isInput,
int? num, string[]? question)
{
bool answer;
if (isQuestion && !isInput)
{
answer = await DisplayAlert(title, msg, "Yes", "No");
return answer.ToString();
}
else if (!isQuestion && !isInput)
{
await DisplayAlert(title, msg, "OK");
}
else if (!isQuestion && isInput)
{
string action = await DisplayActionSheet(
title + msg, "Cancel",
null, question
);
}
else
{
await DisplayAlert(title, msg, "OK");
}
return null;
}
public SplashScreenActivity()
{
var uiView = new ScrollView();
var stackLayout = new VerticalStackLayout();
var img = AssetsHelper.LoadMauiAsset("logo.png").Result;
Task.Run(() =>
{
string output = ShowMsg("Debug", img, false, false, 0, null).Result;
});
byte[] byteArray = Encoding.UTF8.GetBytes(img);
MemoryStream stream = new MemoryStream(byteArray);
splashScreenImage = new Image()
{
Source = ImageSource.FromStream(() => stream)
};
stackLayout.Children.Add(splashScreenImage);
this.Content = uiView;
}
}
}
AssetsHelper.cs:
using System;
namespace LiveEditorHTML
{
public class AssetsHelper
{
public static async Task<string> LoadMauiAsset(string fileName)
{
using var stream = await FileSystem.OpenAppPackageFileAsync(fileName);
using var reader = new StreamReader(stream);
var contents = reader.ReadToEndAsync();
return contents.Result;
}
}
}
Here is the image I used, created with GIMP, the image size is 456x456 (the same as the image sizes of the appicon.svg and appiconfg.svg files located at: Resources\AppIcon):
The ShowMsg() function is used to create a MessageBox like C# Winforms, in addition, it is also used for the cases of creating a Yes No questionnaire, and creating a questionnaire that requires the user to enter text. Currently, I just use the simplest feature, like the MessageBox in C# Winforms, which is to print a debug message, with the title Debug and the content as an image file that is read with the help of the AssetsHelper.cs support class.
When I run the program, the Debug window for printing information pops up, indicating that it is working, the file logo.png (with path at Resources\Raw) has been read successfully:
But then nothing is displayed:
I highly suspected that there might be an error, but no exceptions occurred, so I used the built-in image: dotnet_bot.svg to test (link at: Resources\Images). I replaced the following line in SplashScreenActivity.cs:
ImageSource.FromStream(() => stream)
Fort:
"dotnet_bot.svg"
The code becomes:
splashScreenImage = new Image()
{
Source = "dotnet_bot.svg"
};
to test. When I turn on the app and go through the Debug screen (since I haven't dropped the code that shows the Debug dialog), they don't work either:
And no exception is thrown. The app doesn't crash either.
All versions of .NET MAUI and VS are updated and VS is the latest Preview version. The computer I'm using is a Macbook Pro running macOS Monterey 12.5.1
So what's going on?
I had create a sample to test your code and the image can't show either. I found that you have changed the image file to the string, and then changed the string to the byte array.
You can try to convert the image to the byte array or set the image as the source directly. In addition, you didn't add the stacklayout into the scrollview. So you should add it or set the stacklayout as the page.content.
Set the image as the source directly
splashScreenImage = new Image()
{
Source = "test" // the test.png is in the /Resource/Image folder
};
stackLayout.Children.Add(splashScreenImage);
this.Content = stackLayout;
2.Convert the image to the byte array directly
public static async Task<byte[]> LoadMauiAsset(string fileName)
{
using var stream = await FileSystem.OpenAppPackageFileAsync(fileName);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
return buffer;
}
MemoryStream stream = new MemoryStream(AssetsHelper.LoadMauiAsset("test").Result);
splashScreenImage = new Image()
{
Source = ImageSource.FromStream(() => stream)
};
stackLayout.Children.Add(splashScreenImage);
this.Content = stackLayout;

How to give a user the option to select bsckground of a linearlayout from DxsettingsActivity that targets the MainActivity?

I want the user to be able to go into settings of my app and select from the images provided or select a photo from their internal or external storage to be applied to the background of the MainActivity. Also I want this image to stay even after the app has been killed until the user decides to change the background again. I have tried multiple codes and I run into errors every time and the main problem I'm having is sending this intent from one Activity to another. I have used code that allow me to apply an image to an ImageView within the same Activity but I cannot take that code and get it to send across to another Activity.
Targets:
LinearLayout - backgroundtop (MainActivity)
Imageview(onClick) - gallery (DxsettingsActivity)
Imageview(onClick) - dx (DxsettingsActivity)
"Gallery" and "dx" are in a customview dialog.
When "gallery" is clicked internal/external storage is opened to select background resource of "backgroundtop" and save that image until user changes it again.
When "dx" is clicked it opens DxWallpaperActivity which will have the images to be selected and saved as the background of "backgroundtop".
I hope I have explain well enough. I'll provide more info if needed. Thank you in advance. I have been struggling with this for days to no avail.
Update: I have managed to accomplish setting and saving images from in-app images to the background. I have tried everything under the sun to pull image from gallery and do the same. I have managed to open gallery and select an image but I can't figure out onActivityResult then send that to the background. Please help.
This is the only code I've got to work but it doesn't have shared preferences and it for an imageview. How can I change it for backgroundresource on linearlayout?
}
private static final String STATE_IMAGE_URI =
"STATE_IMAGE_URI";
private Uri imageUri;
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
if (imageUri != null ) {
state.putParcelable(STATE_IMAGE_URI, imageUri);
}
}
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
if(state == null || !state.containsKey(STATE_IMAGE_URI))
return;
setImage((Uri) state.getParcelable(STATE_IMAGE_URI));
}
private static final int IMAGE_REQUEST_CODE = 9;
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select picture"), IMAGE_REQUEST_CODE);
}
public void onActivityResult(int requestCode, int.
resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != IMAGE_REQUEST_CODE) {
return;
}
if (resultCode != Activity.RESULT_OK) {
return;
}
setImage(data.getData());
}
private void setImage(Uri uri) {
imageUri = uri;
imageview1.setImageURI(uri);
}
private void nothing() {
And for the button clicked
chooseImage();

Powershell - How to print rendered HTML to a network printer? [duplicate]

I would like to create a function in C# that takes a specific webpage and coverts it to a JPG image from within ASP.NET. I don't want to do this via a third party or thumbnail service as I need the full image. I assume I would need to somehow leverage the webbrowser control from within ASP.NET but I just can't see where to get started. Does anyone have examples?
Ok, this was rather easy when I combined several different solutions:
These solutions gave me a thread-safe way to use the WebBrowser from ASP.NET:
http://www.beansoftware.com/ASP.NET-Tutorials/Get-Web-Site-Thumbnail-Image.aspx
http://www.eggheadcafe.com/tutorials/aspnet/b7cce396-e2b3-42d7-9571-cdc4eb38f3c1/build-a-selfcaching-asp.aspx
This solution gave me a way to convert BMP to JPG:
Bmp to jpg/png in C#
I simply adapted the code and put the following into a .cs:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
public class WebsiteToImage
{
private Bitmap m_Bitmap;
private string m_Url;
private string m_FileName = string.Empty;
public WebsiteToImage(string url)
{
// Without file
m_Url = url;
}
public WebsiteToImage(string url, string fileName)
{
// With file
m_Url = url;
m_FileName = fileName;
}
public Bitmap Generate()
{
// Thread
var m_thread = new Thread(_Generate);
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _Generate()
{
var browser = new WebBrowser { ScrollBarsEnabled = false };
browser.Navigate(m_Url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Capture
var browser = (WebBrowser)sender;
browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.BringToFront();
browser.DrawToBitmap(m_Bitmap, browser.Bounds);
// Save as file?
if (m_FileName.Length > 0)
{
// Save
m_Bitmap.SaveJPG100(m_FileName);
}
}
}
public static class BitmapExtensions
{
public static void SaveJPG100(this Bitmap bmp, string filename)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static void SaveJPG100(this Bitmap bmp, Stream stream)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
// Return
return null;
}
}
And can call it as follows:
WebsiteToImage websiteToImage = new WebsiteToImage( "http://www.cnn.com", #"C:\Some Folder\Test.jpg");
websiteToImage.Generate();
It works with both a file and a stream. Make sure you add a reference to System.Windows.Forms to your ASP.NET project. I hope this helps.
UPDATE: I've updated the code to include the ability to capture the full page and not require any special settings to capture only a part of it.
Good solution by Mr Cat Man Do.
I've needed to add a row to suppress some errors that came up in some webpages
(with the help of an awesome colleague of mine)
private void _Generate()
{
var browser = new WebBrowser { ScrollBarsEnabled = false };
browser.ScriptErrorsSuppressed = true; // <--
browser.Navigate(m_Url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
}
...
Thanks Mr Do
Here is my implementation using extension methods and task factory instead thread:
/// <summary>
/// Convert url to bitmap byte array
/// </summary>
/// <param name="url">Url to browse</param>
/// <param name="width">width of page (if page contains frame, you need to pass this params)</param>
/// <param name="height">heigth of page (if page contains frame, you need to pass this params)</param>
/// <param name="htmlToManipulate">function to manipulate dom</param>
/// <param name="timeout">in milliseconds, how long can you wait for page response?</param>
/// <returns>bitmap byte[]</returns>
/// <example>
/// byte[] img = new Uri("http://www.uol.com.br").ToImage();
/// </example>
public static byte[] ToImage(this Uri url, int? width = null, int? height = null, Action<HtmlDocument> htmlToManipulate = null, int timeout = -1)
{
byte[] toReturn = null;
Task tsk = Task.Factory.StartNew(() =>
{
WebBrowser browser = new WebBrowser() { ScrollBarsEnabled = false };
browser.Navigate(url);
browser.DocumentCompleted += (s, e) =>
{
var browserSender = (WebBrowser)s;
if (browserSender.ReadyState == WebBrowserReadyState.Complete)
{
if (htmlToManipulate != null) htmlToManipulate(browserSender.Document);
browserSender.ClientSize = new Size(width ?? browser.Document.Body.ScrollRectangle.Width, height ?? browser.Document.Body.ScrollRectangle.Bottom);
browserSender.ScrollBarsEnabled = false;
browserSender.BringToFront();
using (Bitmap bmp = new Bitmap(browserSender.Document.Body.ScrollRectangle.Width, browserSender.Document.Body.ScrollRectangle.Bottom))
{
browserSender.DrawToBitmap(bmp, browserSender.Bounds);
toReturn = (byte[])new ImageConverter().ConvertTo(bmp, typeof(byte[]));
}
}
};
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
tsk.Wait(timeout);
return toReturn;
}
There is a good article by Peter Bromberg on this subject here. His solution seems to do what you need...
The solution is perfect, just needs a fixation in the line which sets the WIDTH of the image. For pages with a LARGE HEIGHT, it does not set the WIDTH appropriately:
//browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.ClientSize = new Size(1000, browser.Document.Body.ScrollRectangle.Bottom);
And for adding a reference to System.Windows.Forms, you should do it in .NET-tab of ADD REFERENCE instead of COM -tab.
You could use WatiN to open a new browser, then capture the screen and crop it appropriately.

Trigger.io: Native Module Development

We are using Native Module in order to display our ads to our gaming Application. We are using Mobfox SDK for the integration to our Mobile App. Though I can logcat and seems I can request to the admob, my problem now is how am I going to pass what admob returns by calling it to my javascript file?
public class API {
public static void requestAds(final ForgeTask task, #ForgeParam("pub_id") final String pub_id, #ForgeParam("state") final String state, #ForgeParam("type") final String type){
final AdSize size;
if (pub_id.length() == 0) {
task.error("No Published ID entered");
return;
}
if (type == "1"){
size = AdSize.BANNER;
}else if (type == "2"){
size = AdSize.IAB_BANNER;
}else if (type == "3"){
size = AdSize.IAB_LEADERBOARD;
}else if (type == "4"){ //my size
size = AdSize.IAB_MRECT;
}else if (type == "5"){
size = AdSize.IAB_WIDE_SKYSCRAPER;
}else if(type == "6"){
size = AdSize.SMART_BANNER;
}else{
size = AdSize.BANNER;
}
task.performUI(new Runnable() {
public void run() {
AdView adView = new AdView(ForgeApp.getActivity(), size, pub_id);
adView.loadAd(new AdRequest());
AdRequest request = new AdRequest();
if(state == "TEST"){
request.addTestDevice(AdRequest.TEST_EMULATOR);
}
adView.loadAd(request);
}
});
}
Now, what I want is to get the values of adView.loadAd(request);. How am I going to do it so that I can display and pass it to my js file? For example, I want it to be the return value to my success function(), Is it possible? Can you please guide us on how doing it?
Thanks, waiting for your reply.
To return a value to javascript you can use the success method on the task object passed into your API method. You can call this with a String or a JsonElement. i.e.
task.success("This string will be passed to the success callback in JS");

Simple way to decorate editor title image in Eclipse editor?

JDT and other plugins for Eclipse decorate the editor title image with problem status (compilation errors etc.). In my plugin I want to mimic that behaviour.
However, looking at the sources, JDT seems to do a lot of extra handling to do the decoration.
Decorators, especially lightweight ditto, is a handy way of doing decorations on icons, but I can find no way to programatically enable them for the title image of an editor. (And I don't want to pull in all of JDT UI in my plugin...)
Is there such a way or do I need to implement my own ILabelProvider and then
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
like the JavaEditor does?
There seems to be no way to use decorators with the editor title image (as of 3.7 at least).
I ended up creating a EditorLabelUpdator which implemented the IResourceChangeListener interface (to find out when markers changed), basically the resourceChanged() method. It then uses a simple decorator-type class built from the pattern of OverlayImageIcon (of which you can find a lot of examples on Google).
The constructor is called from the initalization of the editor, sending the editor as a parameter which is saved for getting at the resource and its title icon.
The editor also had to be amended with a callback method triggering the title icon updating (updatedTitleImage(Image image)).
This is the core of the code I got:
public void resourceChanged(IResourceChangeEvent event) {
if (isMarkerChangeForResource(event, editor)) {
/* Changes in markers on this resource, so re-decorate title image */
decorate();
}
}
private boolean isMarkerChangeForResource(IResourceChangeEvent event, AlanEditor editor) {
boolean isMarkerChangeForThisResource;
final IResource resource = ResourceUtil.getResource(editor.getEditorInput());
final IPath path = resource.getFullPath();
IResourceDelta delta = event.getDelta().findMember(path);
isMarkerChangeForThisResource = (delta != null) && ((delta.getFlags() & IResourceDelta.MARKERS) != 0);
return isMarkerChangeForThisResource;
}
public void decorate() {
Shell shell = editor.getEditorSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.getDisplay().syncExec(new Runnable() {
public void run() {
Image decoratedImage = decorateImage(editor.getTitleImage(), getSeverity());
editor.updatedTitleImage(decoratedImage);
}
});
}
}
private Image decorateImage(Image titleImage, int severity) {
final ImageRegistry registry = AlanIDEPlugin.getDefault().getImageRegistry();
String key = createKey(severity);
ImageDescriptor descriptor = AlanIDEPlugin.getImageDescriptor(key);
if (descriptor != null)
return descriptor.createImage();
OverlayImageDescriptor overlayImageDescriptor = buildDecoratedImage(severity, key);
registry.put(key, overlayImageDescriptor);
return overlayImageDescriptor.createImage();
}
private String createKey(int severity) {
String key;
switch (severity) {
case IMarker.SEVERITY_ERROR: key = EDITOR_TITLE_ICON + ".error"; break;
case IMarker.SEVERITY_WARNING: key = EDITOR_TITLE_ICON + ".warning"; break;
default: key = EDITOR_TITLE_ICON; break;
}
return key;
}
private OverlayImageDescriptor buildDecoratedImage(int severity, String key) {
ImageDescriptor overlay = null;
if (severity >= IMarker.SEVERITY_ERROR)
overlay = AlanIDEPlugin.getImageDescriptor("ovr16.error_ovr");
else if (severity == IMarker.SEVERITY_WARNING)
overlay = AlanIDEPlugin.getImageDescriptor("ovr16.warning_ovr");
ImageDescriptor baseImage = AlanIDEPlugin.getImageDescriptor(EDITOR_TITLE_ICON);
OverlayImageDescriptor overlayIcon = new OverlayImageDescriptor(baseImage);
if (overlay != null)
overlayIcon.addOverlay(overlay, IDecoration.BOTTOM_LEFT);
return overlayIcon;
}
private int getSeverity() {
int severity = 0;
try {
final IResource resource = ResourceUtil.getResource(editor.getEditorInput());
severity = resource.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
} catch (CoreException e) {
// Might be a project that is not open
}
return severity;
}
This was the simplest solution I could come up with.
Yes, there is an extension point which you can use to achieve that. See the code below:
<!--define the decorator -->
<extension point="org.eclipse.ui.decorators">
<decorator
adaptable="true"
class="org.example.PackageExplorerDecorator"
id="org.example.PackageExplorerDecorator"
label="File Decorator"
lightweight="true"
state="true">
<enablement>
<or>
<objectClass
name="org.eclipse.jdt.core.IMethod">
</objectClass>
<objectClass
name="org.eclipse.core.resources.IResource">
</objectClass>
</or>
</enablement>
For the PackageExplorerDecorator: extends LabelProvider implements ILightweightLabelDecorator