How to load a web page in a WebView by clicking on a button in other stage? - webview

i'm working on a browser with JavaFX i want to load a web page in FXMLFile1 contains WebView just by clicking on Button in FXMLFile2 to show the page in FXMLFile1 i tried this code :
#FXML
public void tabfirst (ActionEvent ee) throws IOException { //for the FXMLFile2's button text.
Socket socket = new Socket();
try {
//open cursor
panoo.setCursor(Cursor.WAIT);
que.setCursor(Cursor.WAIT);
bbb.setCursor(Cursor.WAIT);
//do work
WebEngine myWebEngine = web1.getEngine(); //this web view is in FXMLFile1
myWebEngine.load("https://www.google.com");
}
catch (IOException e){
final Stage stg = new Stage();
stg.initModality(Modality.APPLICATION_MODAL);
stg.initOwner(stg);
stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
labelno.setText("Cannot connect to the internet...");
//set cursor
ancpa.setCursor(Cursor.DEFAULT);
} finally{
try{ socket.close(); } catch (Exception e){ }
}
}
note this class tabfirst is in the Button in the FXMLFile2 and the two FXMLfiles are in the same controller.
so please can any body show me what's wrong with my code and thanks in advance!

I don't think you are setting web1. I think that because the 2 FXML files are using the same controller (Edit: my bad, I misread/misunderstood) you are expecting that they are automatically sharing variables, which they do not !
When the FXMLLoader loads an FXML file it creates a new instance of the controller every time. So the controller instance from FXMLfile1 doesn't know about the controller instance of FXMLfile2 or any of its variables.
There are about 5 different ways of sharing information between controllers:
The simplest is just using getters and setters between the two.
Also fairly simple is to bind properties between the two.
You could setup listeners and then notify them of changes.
Use a messaging bus.
Use injection.
Which one you use depends on various factors and requires more information as to what you are trying to accomplish ?
A basic outline of options 1 & 2 would look something like this:
FXMLLoader fxml1 = .....
fxml1.load();
ctrl1 = fxml1.getController();
FXMLLoader fxml2 = .....
fxml2.load();
ctrl2 = fxml2.getController();
ctrl2.set????( ctrl1.get????() ); // get something from the one and set it in the other
// if the value in ctrl1 changes it does not necessarily change in ctrl2
ctrl2.property????().bind( ctrl1.property???? ); // ctrl2 binds to a property in ctrl1
// if the value of the ctrl1 property changes it WILL also change in ctrl2

Related

How to solve activity not found exception when navigate to other view?

I am getting a Android.Content.ActivityNotFoundException: when I want to go to another activity.
Also I have to recreate my emulator every time I want to see my app because it causes always adb error the second time I start the emulator.
I read that this can be caused by another exception, but I checked a other code and I didnt find anything
Button btnentrar = FindViewById<Button>(Resource.Id.createlist);
btnentrar.Click += delegate
{
StartActivity(typeof(listeditorclass));
};
//activity:
private List<string> mItems;
private ListView mListView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.listeditor);
mListView = FindViewById<ListView>(Resource.Id.listView);
mItems = new List<string>();
mItems.Add("Milch");
mItems.Add("Brot");
mItems.Add("Apfel");
MyListViewAdapter adapter = new MyListViewAdapter(this, mItems);
mListView.Adapter = adapter;}
also I dont know the diffrents between AppCompatActivity and a normal activity. So general the user should see when he clicks on the button the new view (createlist) with my list.
I hadn't used anonymous delegates on Xamarin before, that's a cool thing. Try using an intent and passing the Context:
btnentrar.Click += delegate
{
StartActivity(new Intent(this, typeof(listeditorclass)));
};

TextView adding a variable string and appending another

I am using IntentExtra to pass three variables from an entry in a RecyclerView from one Activity into a TextView on another Activity (ActivityTwo) using Get Extras. That all works fine and the variables are joined and displayed in the TextView.
TextView mTitle = (TextView) findViewById(R.id.textViewOrderList);
mTitle.append(number + title + (Double) price);
I then navigate back to ActivityOne, select a different item in the RecyclerView and the new variables are sent to ActivityTwo.
However, despite using append, it either a/ overwrites the existing text, OR b/the first set of text is not retained. Am not sure which
I did consider saving the text to a local file and then appending to it each time I enter ActivityTwo. Then loading it into the TextView But this feels like using a steamroller to crack a nut!!
Any solutions much appreciated.
In the end I decided to write to a local file. As I wanted to Append info rather than overwrite I used the MODE_APPEND rather than MODE_PRIVATE.
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_APPEND);
fOut.write(dataTitle.getBytes());
fOut.write('\n');
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

How to open custom dialog box / popup using Xamarin.Forms?

I am newbie to Xamarin.Forms and stuck with a situation where I want to open up a popup box with my control details [e.g. View Employee Details] on click of parent page.
How can I open custom dialog box / popup using Xamarin.Forms?
Any example code will be appreciated?
Thanks in advance!
If you still want to have your popup's code in its own Page you can set up some custom renderers along the following logic.
1. A ModalPage & corresponding renderer
public class ModalPage : ContentPage { }
public class ModalPageRenderer : PageRenderer {
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
this.View.BackgroundColor = UIColor.Clear;
this.ModalPresentationStyle = UIModalPresentationStyle.OverCurrentContext;
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
SetElementSize (new Size (View.Bounds.Width, View.Bounds.Height));
}
}
2. HostPage
public class ModalHostPage : ContentPage, IModalHost
{
#region IModalHost implementation
public Task DisplayPageModal(Page page)
{
var displayEvent = DisplayPageModalRequested;
Task completion = null;
if (displayEvent != null)
{
var eventArgs = new DisplayPageModalRequestedEventArgs(page);
displayEvent(this, eventArgs);
completion = eventArgs.DisplayingPageTask;
}
// If there is no task, just create a new completed one
return completion ?? Task.FromResult<object>(null);
}
#endregion
public event EventHandler<DisplayPageModalRequestedEventArgs> DisplayPageModalRequested;
public sealed class DisplayPageModalRequestedEventArgs : EventArgs
{
public Task DisplayingPageTask { get; set;}
public Page PageToDisplay { get; }
public DisplayPageModalRequestedEventArgs(Page modalPage)
{
PageToDisplay = modalPage;
}
}
}
3. HostPage renderer
public class ModalHostPageRenderer: PageRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if(e.OldElement as ModalHostPage != null)
{
var hostPage = (ModalHostPage)e.OldElement;
hostPage.DisplayPageModalRequested -= OnDisplayPageModalRequested;
}
if (e.NewElement as ModalHostPage != null)
{
var hostPage = (ModalHostPage)e.NewElement;
hostPage.DisplayPageModalRequested += OnDisplayPageModalRequested;
}
}
void OnDisplayPageModalRequested(object sender, ModalHostPage.DisplayPageModalRequestedEventArgs e)
{
e.PageToDisplay.Parent = this.Element;
var renderer = RendererFactory.GetRenderer (e.PageToDisplay);
e.DisplayingPageTask = this.PresentViewControllerAsync(renderer.ViewController, true);
}
}
Then it is as simple as calling
await ModalHost.DisplayPageModal(new PopUpPage());
from your host page or in this particular case from the ViewModel behind.
What Pete said about PushModalAsync / PopModalAsync still remains valid for this solution too (which in my opinion is not a disadvantage), but your popup would appear with transparent background.
The main advantage of this approach, in my opinion, is that you can have your popup XAML/code definition separate from the host page and reuse it on any other page where you wish to show that popup.
The general purpose of what you are trying to achieve can be accomplished by using the PushModalAsync and PopModalAsync methods of Xamarin.Forms Navigation object.
The chances are that this is good enough for what you are needing - However - this isn't truely modal. I will explain after a small code snippet:-
StackLayout objStackLayout = new StackLayout()
{
};
//
Button cmdButton_LaunchModalPage = new Button();
cmdButton_LaunchModalPage.Text = "Launch Modal Window";
objStackLayout.Children.Add(cmdButton_LaunchModalPage);
//
cmdButton_LaunchModalPage.Clicked += (async (o2, e2) =>
{
ContentPage objModalPage = new ContentPage();
objModalPage.Content = await CreatePageContent_Page2();
//
await Navigation.PushModalAsync(objModalPage);
//
// Code will get executed immediately here before the page is dismissed above.
});
//
return objStackLayout;
private async Task<StackLayout> CreatePageContent_Page2()
{
StackLayout objStackLayout = new StackLayout()
{
};
//
Button cmdButton_CloseModalPage = new Button();
cmdButton_CloseModalPage.Text = "Close";
objStackLayout.Children.Add(cmdButton_CloseModalPage);
//
cmdButton_CloseModalPage.Clicked += ((o2, e2) =>
{
this.Navigation.PopModalAsync();
});
//
return objStackLayout;
}
The problem with the above is that the
await Navigation.PushModalAsync(objModalPage);
will immediately return after the animation.
Although you can't interact with the previous page, as we are displaying a new NavigationPage with a Close button shown - the parent Navigation Page is still executing behind the scenes in parallel.
So if you had any timers or anything executing these still would get called unless you stopped those.
You could also use the TaskCompletionSource approach as outlined in the following post also How can I await modal form dismissal using Xamarin.Forms?.
Note - that although you can now await the 2nd page displaying and then when that page is dismissed allowing code execution to continue on the next line - this is still not truely a modal form. Again timers or anything executing still will get called on the parent page.
Update 1:-
To have the content appear over the top of existing content then simply include it on the current page, however make this section of content invisible until you need it.
If you use an outer container such like a Grid that supports multiple child controls in the same cell, then you will be able to achieve what you want.
You will also want to use something like a filled Box with transparency that will cover the entire page also, to control the visible, see through section, that surrounds your inner content section.
I followed above approach and found it impossible to run on iOS 7.
I found this library BTProgressHUD which you can modify and use.
I Use its methods by Dependency service.
Actual library for popups.
https://github.com/nicwise/BTProgressHUD
Following example uses BTProgressHUD library internally.
https://github.com/xximjasonxx/ScorePredictForms

Popup Print Window in Vaadin 7 with Table

I am new on Vaadin.
How to pass Table component to new popup screen in Vaadin 7? Assume I already created table using com.vaadin.ui.Table.
Table aaa = new Table();
Currently Vaadin tutorial just show how to create print popup without pass component/data.
Based on below code
public static class PrintUI extends UI {
#Override
protected void init(VaadinRequest request) {
// Have some content to print
setContent(new Label(
"<h1>Here's some dynamic content</h1>\n" +
"<p>This is to be printed.</p>",
ContentMode.HTML));
// Print automatically when the window opens
JavaScript.getCurrent().execute(
"setTimeout(function() {" +
" print(); self.close();}, 0);");
}
}
...
// Create an opener extension
BrowserWindowOpener opener =
new BrowserWindowOpener(PrintUI.class);
opener.setFeatures("height=200,width=400,resizable");
// A button to open the printer-friendly page.
Button print = new Button("Click to Print");
opener.extend(print);
Appreciated if someone could show me how to pass Table aaa into PrintUI class.
Window window = new Window("my test table popup");
window.setContent(table);
window.setModal(true);
getUI().addWindow(window);
The only way that I have found to pass objects to the UI class in popup window is to store them in session:
Table table = new Table();
VaadinSession.getCurrent().setAttribute("table", table);
In the popup window:
Table t = (Table) VaadinSession.getCurrent().getAttribute("table");
You can also initialize your Table in your PrintUI class. If you need to initialize a specific Table instance, you can pass, let's say, your table id parameter to the UI via .getParameter("idTable") (which, in the end, works as adding a GET parameter to the URL) and then retrieve it in your PrintUI's init() method via the request parameter with .getParameter("idTable").

Monotouch.Dialog - How to push a view from an Element

It seems like this should be very easy, but I'm missing something. I have a custom Element:
public class PostSummaryElement:StyledMultilineElement,IElementSizing
When the element's accessory is clicked on, I want to push a view onto the stack. I.e. something like this:
this.AccessoryTapped += () => {
Console.WriteLine ("Tapped");
if (MyParent != null) {
MyParent.PresentViewController(new MyDemoController("Details"),false,null);
}
};
Where MyDemoController's gui is created with monotouch.dialog.
I'm just trying to break up the gui into Views and Controlls, where a control can push a view onto the stack, wiat for something to happen, and then the user navigates back to the previous view wich contains the control.
Any thought?
Thanks.
I'd recommend you not to hardcode behavior in AccessoryTapped method, because the day when you'll want to use that component in another place of your project is very close. And probably in nearest future you'll need some another behavior or for example it will be another project without MyDemoController at all.
So I propose you to create the following property:
public Action accessoryTapped;
in your element and its view, and then modify your AccessoryTapped is that way:
this.AccessoryTapped += () => {
Console.WriteLine ("Tapped");
if (accessoryTapped != null) {
accessoryTapped();
}
};
So you'll need to create PostSummaryElement objects in following way:
var myElement = new PostSummaryElement() {
accessoryTapped = someFunction,
}
...
void someFunction()
{
NavigationController.PushViewController (new MyDemoController("Details"), true);
}

Resources