Memory not released in PopUp xamarin forms android application - memory

I am using a popup to show a image popup in xamarin forms android application. Each time when i open and close the popup the memory spikes and this is not recollected. I am using a constructor to open the popup. How can we properly dispose the memory inside the popup when its closed.
//call from the parent page
await Navigation.PushPopupAsync(new ImagePopUp(imgSrc));
//ImagePopUp
public ImagePopUp()
{
InitializeComponent();
var tapgesture = new TapGestureRecognizer();
tapgesture.Tapped += async (sender, e) => Handle_Clicked(sender, e);
this.Content.GestureRecognizers.Add(tapgesture);
}
public ImagePopUp(ImageSource src) : this()
{
try
{
PopUpImageHolder.HeightRequest = App.ScreenHeight * 0.8;
if (src != null)
{
PopUpImageHolder.Source = src;
}
}
catch (Exception ex)
{
Task.Run(async () => await DisplayAlert("Alert", ex.Message, "OK"));
}
and to close the popup i use
await PopupNavigation.PopAsync();
The image memory is spiking each time when i open the popup

Related

UIActivityIndicator is not working correctly Xamarin IOS

I am including UIActivityIndicator in my UIViewController.
I need to bring a file from FTP using.
I have a button on my ViewController, upon clicking that button, download will start. I put a UIActivityIndicator (aiReceive) on my ViewController, That is appearing in stopped state on my view controller, but only animate upon completing file download.
I am making a iPad App in Xamarin IOS.
I added the Async Method, but i am getting the below error now.
The await operator can only be used when its containing lambda expression is marked with the async modifier
public partial class FirstViewController : UIViewController
{
public override void ViewDidLoad()
{
base.ViewDidLoad();
btnReceiveData.TouchUpInside += (object sender, EventArgs e) =>
{
//BTProgressHUD.Show("Receiving Data..."); --> This Component is also not working,
aiReceive.StartAnimating();
await GetFileAsync());
BTProgressHUD.Dismiss();
};
}
async Task GetFileAsync()
{
using (var client = new HttpClient())
{
try
{
aiReceive.StartAnimating(); /* --> Inimation is not starting at this point. Animation Start After Downloading file, download takes time, i want to show animation in the mean while.*/
using (WebClient ftpclient = new WebClient())
{
try
{
ftpclient.Credentials = new System.Net.NetworkCredential("UserName", "Password");
string sourceFilePath = #"ftp://ftp.google.com/FileName.pdf";
var FileDownloadStart = UIAlertController.Create("Info", "Data file received.", UIAlertControllerStyle.Alert);
FileDownloadStart.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(FileDownloadStart, true, null);
//Downloading file from FTP.
ftpclient.DownloadFile(sourceFilePath, "C:\");
var FileDownloadAlert = UIAlertController.Create("Info", "Data file received.", UIAlertControllerStyle.Alert);
FileDownloadAlert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(FileDownloadAlert, true, null);
}
catch (Exception ex)
{
File.Delete(EpazzDirectory + AuditorId.ToString());
var ExceptionAlert = UIAlertController.Create("Exception", ex.Message, UIAlertControllerStyle.Alert);
ExceptionAlert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(ExceptionAlert, true, null);
}
}
}
}
}
}
You're blocking the UI thread, and that will prevent the changes you want to make to the UI from taking effect (in this case UIActivityIndicator spinning animation).
The best way to do this is using async/await like:
aiReceive.StartAnimating();
await YourFTPRequestAsync();
aiReceive.StopAnimating();
Here are official MSDN documentation on async\await and a sample driven hint on how it works

How to load a web page in a WebView by clicking on a button using JavaFX?

i'm working on a browser and i have a button that button while clicking on it should loads a web page on WebView this is the code that i've traied:
#FXML
private void tabfirst (ActionEvent ee) throws IOException { // for tha Chooser frame text.
String hh = text11.getText();
Socket socket = new Socket();
try {
web1.setVisible(true);
//open cursor
panoo.setCursor(Cursor.WAIT);
que.setCursor(Cursor.WAIT);
//add
ancpa.setCursor(Cursor.WAIT);
web1.setCursor(Cursor.WAIT);
web2.setCursor(Cursor.WAIT);
web3.setCursor(Cursor.WAIT);
web4.setCursor(Cursor.WAIT);
web5.setCursor(Cursor.WAIT);
web6.setCursor(Cursor.WAIT);
web7.setCursor(Cursor.WAIT);
web8.setCursor(Cursor.WAIT);
web9.setCursor(Cursor.WAIT);
//do work
URL url = new URL (hh);
url.getContent();
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load(url.toString());
//close the window chooser
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
Scene scene = new Scene(root);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//close cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
}
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...");
//close chooser
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//set cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
} finally{
try{ socket.close(); } catch (Exception e){ }
}
}
So what's the problem with this code please can anybody help me and thank you soooo much!
Hmm...
Instead of
myWebEngine.load(url.toString());
do
myWebEngine.load(url.toExternalForm());
... anyway, what's the output in the console? Is there any exception/error popping up?

How to stop progressbar in blackberry

In BlackBerry, my application is working perfectly fine. But one Requirement is when I load data from server, a progress bar is showing. If it takes so much time to load data from server, then I want to stop the progress bar. In BlackBerry, on back key pressed, it is not working. Please help me.
public class WaitScreen extends PopupScreen
{
public WaitScreen(String msg) {
super(new HorizontalFieldManager());
add(new LabelField(msg));
AnimatedGIFField testanimated = new AnimatedGIFField(
(GIFEncodedImage) (GIFEncodedImage.getEncodedImageResource("ajax_loader.gif")),
AnimatedGIFField.FIELD_HCENTER | AnimatedGIFField.FIELD_VCENTER);
add(testanimated);
}
}
public long timeout=0;
t.schedule(new TimerTask() {
public void run()
{
// TODO Auto-generated method stub
timeout+=1;
System.out.println("Timeout value:"+timeout);
if(timeout>=28)
{
//timeout every 1 munite
System.out.println("Timeout value:"+timeout);
System.out.println("closing connection");
try
{
parent.notifyDestroyed();
}
catch (Exception ex)
{
System.out.println("Exception is:"+ex);
}
this.cancel();
}
}
}, 0, 1000);
// Thread.sleep(30000);
httpconn_post = (HttpConnection) Connector.open(url);
httpconn_post.setRequestMethod(HttpConnection.POST);
httpconn_post.setRequestProperty("Accept_Language","en-US");
httpconn_post.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = httpconn_post.openOutputStream();
out.write(param.getBytes());
out.flush();
System.out.println("Status Line Code: " + httpconn_post.getResponseCode());
System.out.println("Status Line Message: " + httpconn_post.getResponseMessage());
if ( httpconn_post.getResponseCode()== HttpConnection.HTTP_OK )
{
is=httpconn_post.openDataInputStream();
// cancelling timer
t.cancel();
.....
.....
}
I had done this using this code..I had done it successfully..

Audio Recording Not Getting setRecordLocation()

I am trying to save audio at a specified device location on Button Click (which invokes run() method). This is my code.
public Audio() {
}
public void run()
{
try{
try{
_player = Manager.createPlayer("capture://audio?encoding=audio/amr");
}
catch(MediaException e)
{
Dialog.alert(e.toString());
}
_player.realize();
_rControl =(RecordControl)_player.getControl("RecordControl");
try{
**//Point 1//**_rControl.setRecordLocation("file:///Device Memory/samples/ringtones/recordTest1.amr");
}
catch(MediaException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
_rControl.startRecord();
_player.start();
System.out.println("<<--Successful-->>>");
}
catch(Exception e){e.printStackTrace();}
}
public void stop()
{
try{
if(_rControl != null)
{
_rControl.stopRecord();
try{
_rControl.commit();
}catch(Exception e){e.printStackTrace();}
_rControl = null;
}
if(_player != null)
{
_player.close();
_player=null;
}
}catch(Exception e){e.printStackTrace();}
}
In run() method, i am getting IOException at Point 1 where i am trying to set location for audio file. But when I tried this:
{
_rControl.setRecordLocation("file:///system/samples/ringtones/recordTest1.amr");
}
i found it working with 9550 simulator but not with 8900 simulator. So what location should i set to make this working with 8900 simulator and also 8900 blackberry device?
You should use:
javax.microedition.io.file.FileSystemRegistry.listRoots()
to get available root file systems on the device running the code.

problems in silverlight 4 when using Action callbacks to check for successful file upload

So the async requirement for silverlight ends up in some really convoluted code!!
Im uploading a file just exactly like this answer suggests.
The difference is Im posting the file to an MVC action method. Everything works file except, like I commented on the bottom of that answer, I don't get any callback for when the file DOES NOT successfully upload.
So I created another action method in my mvc app (Services/CheckForFile/{id}) and it returns a string depending on whether the file is found.
Now, how and when do I call this mvc action method is the problem:
void DoUpload() { //Gets call on BtnUpload.Click
//opn is an OpenFileDialog
up.UploadFile(_filename, opn.File.OpenRead(),
e =>
{
//do some ui stuff here.
BeginCheck();// calling this causes PROBLEMS!
});
}
private void BeginCheck()
{
Uploader up = new Uploader();
up.CheckForFile(_filename, success =>
{
if (!success)
{
MessageBox.Show("There was problem uploading the file. Please try again", "Error", MessageBoxButton.OK);
}
});
}
Here is the problem:
When the BeginCheck() function runs, the file, for some reason, NEVER uploads! If I comment it out it does!? It seems like The BeginCheck() runs during the upload or something? Shouldn't it run after!?
How/where would I call BeginCheck() after the upload, to ensure the file has been uploaded?
Here is how I defined the Uploader class:
public class Uploader
{
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
callback(null);//this ALWAYS hits!
}
catch (Exception err)
{
if (callback != null)
{
callback(err);
}
}
};
c.OpenWriteAsync(ub.Uri);
}
public void CheckForFile(string filename, Action<bool> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/CheckForFile/" + fileName);
WebClient c = new WebClient();
c.OpenReadCompleted += (sender, e) =>
{
using (StreamReader sw = new StreamReader(e.Result))
{
if (sw.ReadToEnd().Equals("Found", StringComparison.InvariantCultureIgnoreCase))
{
callback(true);
}
else
{
callback(false);
}
}
};
c.OpenReadAsync(ub.Uri);
}
private void PushData(Stream input, Stream output)
{//4KB is not a limitation. We only copy 4Kb at a time from in to out stream
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
I'm embarrased to say that the original answer of mine to which you refer isn't entirely accurate. It seems to work for what the OP wanted but in fact the code doesn't block at the point that I thought it did. In reality what you are actually looking for is the WriteStreamClosed event, its here that you can discover any failure of the request.
Here is an ammended version that works the way you are expecting:-
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
}
catch (Exception err)
{
if (callback != null)
callback(err);
}
};
c.WriteStreamClosed += (sender, e) =>
{
if (callback != null)
callback(e.Error);
}
c.OpenWriteAsync(ub.Uri);
}
Now your BeginCheck will only run after the server has responded to the file upload.

Resources