Out of memory imageview - imageview

I'm developing an application with a menu which contains a list of buttons, when you click one of these buttons, another activity (the same activity with different image for each button) is opened showing an imageview. The problem is that when i click several times in different buttons (opening new images) the app crashes and i'm not able to solve it. Any help? Thanks.

That problem is because your are using a lot of images in your views and never clean the memory, then in one momento your don't have more memory for the new ones.
One form to resolve that problem is cleaning the memory always your destroy and activity.
You can override the next method in your activity for clean the memory.
#Override
public void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
that method review a view, in your case those views will be your ImageView and ImageButton.
Finally you need call this method in the method onDestroy() (need override that method too).

Related

Xamarin Forms AppShell How return to previous page

I see a lot of threads on this sort of subject but none seem to apply to my question. I don't have a navigation page, I have a hamburger menu -- so Push/PopAsync() would not appear to be the answer. And I don't want to go to a specific page, I want to go back to the previous page (whatever it was) so GoToAsync() would not appear to be the answer.
Xamarin app for Android and UWP with iOS somewhere in the future. The description of the problem below is specific to Android; it works a little differently on UWP.
I want to put a Help entry in the hamburger menu that will take the user to a help page in the default browser. Hamburger menu seems to only go to an app page, so I defined a "dummy" View page that displays "Loading ..." and issues Browser.OpenAsync() in its OnAppearing() method, and that pretty much works. The problem is that the user would expect that the Back button would take him or her to the page they were on before clicking Help. I tried a couple of things. I have gotten close with the following but it does not quite work correctly:
In each of my other Views' OnAppearing() I call a method that saves the value of Current.MainPage.CurrentItem in a static. Then in the Help page after the OpenAsync() I set Current.MainPage.CurrentItem to its setting from the last page before the Help page.
Console.WriteLine("#### HelpPage loading Web Help");
_ = State.DisplayHelpPage(this, "MainHelp"); // _ = await Browser.OpenAsync(uri, blo);
Console.WriteLine("#### HelpPage returning to previous page");
State.ReloadPreviousPage(); // Current.MainPage).CurrentItem = lastFlyoutItem;
It almost works. The first time I click Help in the hamburger menu I get
#### HelpPage loading Web Help
#### HelpPage returning to previous page
#### HelpPage loading Web Help
#### HelpPage returning to previous page
The Web page loads perfectly. But when I click the Back button it displays again. Obviously my OnAppearing() method has been driven twice, which I do not understand.
If I click the Back button again I come back to the previous page in the application just as I wanted. The next time I click Help in the Hamburger menu it takes me to my dummy View page with no Web page. Obviously, my OnAppearing() is not being driven at all. But after that it works perfectly. I can go to any app page, and click Help in the menu. I get the Web page, and the Back button takes me back to the app and the page. In UWP of course the browser does not load on top of the app Views, and I seem to see it being loaded twice every time.
So ... what should I be doing differently? And why is my OnAppearing() being driven twice and then not at all ... and thereafter as I would expect?
There are several parts to this answer:
Get the previous page on to the Navigation stack. This is done by intercepting the Route "//HelpPage", and replacing it with a route that ISN'T a child of Shell.
Remember "FakePageVisible", so we know to do "PopAsync" in OnResume, when app returns from browser.
(Optional) "Entering" flag prevents going to browser twice.
App.xaml.cs:
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new AppShell();
}
protected override void OnResume()
{
if (HelpPage.FakePageVisible) {
HelpPage.FakePageVisible = false;
var shell = MainPage as AppShell;
if (shell != null) {
shell.Navigation.PopAsync();
}
}
}
}
AppShell.xaml.cs:
public partial class AppShell : Xamarin.Forms.Shell
{
public AppShell()
{
InitializeComponent();
// Define a route that isn't a child of Shell.
Routing.RegisterRoute("Help2", typeof(HelpPage));
}
protected override void OnNavigating(ShellNavigatingEventArgs args)
{
base.OnNavigating(args);
if (args.Current != null) {
if (args.Source == ShellNavigationSource.ShellItemChanged) {
if (args.Target.Location.OriginalString == "//HelpPage") {
// Cancel the original route.
args.Cancel();
Device.BeginInvokeOnMainThread(() => {
// Used by the next OnAppearing.
HelpPage.Entering = true;
// Go there by a route that isn't a child of Shell.
// Doing so, pushes our previous location on to Navigation stack.
Shell.Current.GoToAsync("Help2");
});
}
}
}
}
}
HelpPage.xaml.cs:
public partial class HelpPage : ContentPage
{
public static bool Entering;
public static bool FakePageVisible;
protected override void OnAppearing
{
// Make sure this only happens once (just in case).
if (Entering) {
Entering = false;
FakePageVisible = true;
Xamarin.Essentials.Browser.OpenAsync("https://aka.ms/xamarin-quickstart");
}
}
}
For a simple demo, this code communicates via static variables in HelpPage. Re-factor as appropriate for your situation.

Navigation issue in Xamarin Forms with same page type multiple time

Relatively new to Xamarin, hitting an issue with PushAsync and navigation I can't figure out.
I have a main navigation page, and then a "MyContentPage" that is responsible for rendering a dynamic list based on a supplied id. When the user clicks on a list item they go to a next (newed up) "MyContentPage" (same class) with a different id. Basically a recursive page hierarchy based on a local db.
Problem is that navigation seems to quickly get messed up in some way I can't work out. The pages get swapped around, or get lost. Navigating back to root, if I click back down again, it skips to a page that is further down etc.
So basically the one page apart from the main page (which has multiple navigationpages in tabs - though I only use one tab at this point) binds its controls to this function:
public async Task NavigateToContent(int contentId)
{
await ((Application.Current.MainPage) as TabbedPage)?.CurrentPage.Navigation.PushAsync(new MyContentPage(contentId));
}
The above is then used recursively. Ie. Similar controls bind to the same function until there are no further pages to click down to.
The MyContentPage constructor loads the model:
public MyContentPage(int id)
{
InitializeComponent();
_id = id;
BindingContext = viewModel = new ContentPageViewModel(id);
}
What is the issue here?
From what you mentioned in comments, the issue is caused by the navigation code called in the 'service' class. When you call the service method multiple times, it actually changes the current navigation stack in xamarin forms. Move the page navigation code from service class to viewmodel class.
Or try to put the page navigation source code into something like 'NavigationService' (one example is the one in https://learn.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/ ) and inject this service into your view model class.
OK so this all turned out to be an issue with concurrency.
The original button click was like this:
private void Button_Clicked(object sender, EventArgs e)
{
Task.Run(async () => await (BindingContext as ContentPageViewModel).ExecuteNavCommand(sender));
}
But this resulted in a UI operation happening on a different task
The event handler can be declared as async
The correction is
private async void Button_Clicked(object sender, EventArgs e)
{
await viewModel.ExecuteNavCommand(sender);
}

javafx reused pane initalization

Here's my situation. I have a javafx pane which I don't want to recreate each time I show it, because I want to keep all filled by user fields in between switching between views.
For that purpose I did this:
#FXML
private void initialize() {
createOrderPane = FxmlUtils.fxmlLoader(CREATE_ORDER_FXML);
}
public void setCenter(String fxmlPath) {
if(CREATE_ORDER_FXML.equals(fxmlPath)) {
borderPane.setCenter(createOrderPane);
}
else {
borderPane.setCenter(FxmlUtils.fxmlLoader(fxmlPath));
}
}
so in case user wants to see CREATE_ORDER_FXML it doesn't reload it, but uses already existing instance.
The problem is that some parts of the view should be reinitalized. For example database might change and I want to refresh some comboboxes which reads value from DB. How to achieve that?
Is there some onShow property? Or maybe I am able to get to the controller of createOrderPane object?

Xamarin Forms - Duplicate Screens

I'm writing an app using Xamarin Forms and I have an issue I was hoping someone can help with.
My app contains a screen which has multiple icons that can be pressed which would then open a new screen.
My issue is that if you press the icon twice really fast, the app opens up 2 instances of the same screen (it's not just related to a double press, if you press the icon 6 times very fast it will open up 6 duplicate screens). Pressing the Back button, closes the top screen to reveal the duplicate screen underneath. Pressing the Back button again navigates you back to the original screen.
This issue seems to occur on any screen within my app so I'm hoping other people will have experienced it and know of a solution to prevent duplicate screens being displayed.
This is a known issue in TapEvents.
My hack is, in the code-behind, have a bool variable _canTap.
Inside the method you are calling to push new page, first you check if canTap, then set to false, and only set to true after navigating to another page. This way all taps will be disregarded.
Example:
private bool _canTap = true;
public void YourMethod()
{
if(_canTap)
{
_canTap = false;
YourMethodToNavigate();
_canTap = true;
}
}
In the Icon_Pressed method add this,
this.IsEnabled = false;
await Navigation.PushAsync(new MyPage());
this.IsEnabled = true;
It disables the page until the current Icon pressed event is finished
This is known problem with Xamarin apps. I've used a private variable combined with a try-finally pattern to solve this. Ex:
bool allowTap = true;
public void ButtonTapped()
{
try
{
if(allowTap)
{
allowTap = false;
// Do whatever...
}
}
finally
{
allowTap = true;
}
}
The finally makes sure allowTap gets set back to true no matter what happens, short of a complete crash. Note that you can also use a catch block between the try and finally blocks to grab any errors if needed.

How to handle up button in toolbar - Kotlin

I have manually/programmatically set up an up button in my toolbar for a fragment page with the following code in onCreateOptionsMenu in the fragment:
(activity as AppCompatActivity).setSupportActionBar?.setDisplayHomeAsUpEnabled(true)
Tapping the system back button will take the user back to the previous fragment but without an up button (that works) I think some users may get lost.
I am having difficulty trying to work out how to catch and handle the up button to pop the fragment off the back stack.
This SO post shows how to catch the the up button click however it is in Java and doesn't go on to explain how you would navigate up.
I think it needs to look something like the code below but there are errors everywhere:
The case android.R.id.home is showing an 'Incompatible types:Int and MenuItem' error?
onBackPressed() is showing an 'Unresolved reference' error.
Bad code:
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item) {
android.R.id.home -> {
onBackPressed()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
UPDATE:
A comment to another SO post has a potential solution in Kotlin. It catches the click on the up button and goes back to the previous fragment page but then the up button doesn't go away. So the up button now persists even on the top level fragment destinations in my app (the pages corresponding to each tab in the BottomNavigationView).
I think this might have to do with the fact that there is only one activity in my app and the way that I have set up the up button in the fragment as mentioned above? If so, is there a workaround or other way to set up the up button by referencing the fragment instead of the whole activity?
If it helps, this is the code in the RecyclerView inner ViewHolder class in the adapter.kt file that navigates to the fragment page in question:
class AdapterListItemDetails(val items: List<ItemsList>) : RecyclerView.Adapter<AdapterListItemDeatils.ItemsViewHolder>() {
//overrides for OnCreateViewHolder, getItemCount, onBindViewHolder
inner class ItemsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var currentItem: ItemsList? = null
var currentPosition: Int = 0
init {
itemView.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.goto_details, null))
}
fun setData(itemsList: ItemsList, position: Int) {
itemView.tview_Keys.text = itemsList!!.nameText
this.currentItem = itemsList
this.currentPosition = position
}
}
}
You have to override onBackPressed() method in activity and handle the fragment transactions with your manual code. If you could share some snippet of activity and fragment transactions will help me to give some proper solution.
Hi this is what i usually do:
in an activity find the navController from your navHostFragment
val navController = this.findNavController(R.id.myNavHostFragment)
Make sure it's connected to the ActionBar
NavigationUI.setupActionBarWithNavController(this, navController)
Then simply override onSupportNavigateUp, find your navController then navigate up
override fun onSupportNavigateUp(): Boolean{
val navController = this.findNavController(R.id.myNavHostFragment)
return navController.navigateUp()
}

Resources