App crashed while creating multiple order?

HarshitaHarshita ✭✭✭✭INMember ✭✭✭✭

I have a order create page,when user create few orders then app getting crashed.
So what is the reason for that?
Should i need to release memory leak?

Answers

  • AlessandroCaliaroAlessandroCaliaro ✭✭✭✭✭ ITMember ✭✭✭✭✭
    You can debug it and take a look to stacktrace
  • JamesLaveryJamesLavery ✭✭✭✭✭ GBBeta, University ✭✭✭✭✭

    What do you mean by 'a few'? 3, 5, 100? It's very unlikely that a memory leak is causing an app crash after just a few operations. It's more likely to be an exception.

    Expanding a bit on @AlessandroCaliaro's comment. If you view Application Output in your IDE, you should see any Exceptions being raised there.

  • HarshitaHarshita ✭✭✭✭ INMember ✭✭✭✭

    @JamesLavery
    After creating 6 orders,apps crashed.
    i already have hockey app,after checking the report it shows:
    java.lang.OutOfMemoryError: Failed to allocate a 245772 byte allocation with 117784 free bytes and 115KB until OOM

  • JamesLaveryJamesLavery ✭✭✭✭✭ GBBeta, University ✭✭✭✭✭

    Wow - so definitely a leak!

    I think we need to see your code. Can you post your XAML and relevant PageModel/Data layer code? Please take care to format it so that it displays correctly on the forum (I suggest you Preview to check before posting).

  • CharwakaCharwaka ✭✭✭✭✭ INMember ✭✭✭✭✭

    @Harshita said:
    @JamesLavery
    After creating 6 orders,apps crashed.
    i already have hockey app,after checking the report it shows:
    java.lang.OutOfMemoryError: Failed to allocate a 245772 byte allocation with 117784 free bytes and 115KB until OOM

    Yeah show the code

  • AlessandroCaliaroAlessandroCaliaro ✭✭✭✭✭ ITMember ✭✭✭✭✭
    Maybe a ListView problem, a Image problem. Post the stack
  • Xami3Xami3 ✭✭✭ PKMember, University ✭✭✭

    @Harshita please upload a sample of your code(at least the page on which you are getting exception). last time i was getting same kind of exception on large images(i have added them in listview). then we made them small in sizes and now it is working fine.

  • HarshitaHarshita ✭✭✭✭ INMember ✭✭✭✭

    Hare is my code:

    public NewWorkOrder()
            {
    InitializeComponent();
     GetAsset();
     GetLocation();
    }
    
    private void GetAsset()
            {
                WORRddlasset.IsEnabled = false;
                AssetInd.IsVisible = true;
                string url = GlobalVariables.ServiceUrl + "/GetAsset/?username=" + GlobalVariables.UserName + "&password=" + 
    .....
                req.BeginGetResponse(new AsyncCallback(FinishAssetWebRequest), req);
            }
     public void FinishAssetWebRequest(IAsyncResult result)
            {
                try
                {
                    HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
                    using (Stream data = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        var ms = new MemoryStream(Encoding.Unicode.GetBytes(text));
                        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(AssetResponse));
                        AssetResponse AssetData = (AssetResponse)deserializer.ReadObject(ms);
    
                        var Assetddl = new List<Asset>();
                        foreach (var Asset in AssetData.Assets)
                        {
    
                            Assetddl.Add(new Asset { Assettagnumber = Asset.Assettagnumber, Name = Asset.Name });
    
                        }
                        Task.Run(() =>
                        {
                            Device.BeginInvokeOnMainThread(() =>
                        {
                            WORRddlasset.ItemsSource = Assetddl;
                            WORRddlasset.IsEnabled = true;
                            AssetInd.IsVisible = false;
                        });
                        });
                    }
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                }
            }
    private void GetLocation()
            {
                string url1 = GlobalVariables.ServiceUrl + "/GetLocation/?username=" + GlobalVariables.UserName + "&password=" + GlobalVariables.Password + "&id=";
                HttpWebRequest req1 = (HttpWebRequest)WebRequest.Create(url1);
                req1.ContentType = "application/json";
                req1.Method = "GET";
                req1.BeginGetResponse(new AsyncCallback(FinishLocationWebRequest), req1);
            }
            public void FinishLocationWebRequest(IAsyncResult result1)
            {
                try
                {
                    HttpWebResponse response1 = (result1.AsyncState as HttpWebRequest).EndGetResponse(result1) as HttpWebResponse;
                    using (Stream data1 = response1.GetResponseStream())
                    using (StreamReader reader1 = new StreamReader(data1))
                    {
                        string text1 = reader1.ReadToEnd();
    
                        var ms = new MemoryStream(Encoding.Unicode.GetBytes(text1));
                        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(LocationResponse));
                        LocationResponse bsObj2 = (LocationResponse)deserializer.ReadObject(ms);
    
    
                        ObservableCollection<Viewlocation> loc = new ObservableCollection<Viewlocation>();
                        foreach (var loctn in bsObj2.Locations)
                        {
                            loc.Add(new Viewlocation { FullpathName = loctn.FullPathName, locationName = loctn.text, pathId = loctn.value, parentId = loctn.parentid });
                            locationId = loctn.value;
                        }
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            LocationView.ItemsSource = loc;
                            hdnLocation.Text = "";
                            hdnPParentLocation.Text = "";
                            valselectedlocation.Text = "";
                        });
    
    
                    }
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                }
            }
    
     private void SaveWorkOrder(object sender, EventArgs e)
            {
                    #region SaveWorkOrder
                    string status = Status.Text;
                    string location = hdnpathid.Text;
                    string parentLocation = hdnParentLocation.Text;
                    string description = Description.Text;
                    string createDate = DateTime.UtcNow.ToString("yyyy/MM/dd");
                    string roomNo = WORRddlroom.Text;
                    string contact = WORRddlcontact.Text;
    
                    string statusCode = GetStatusCode(status);
    
                    string contactEmail = "";
                    if (!string.IsNullOrEmpty(contactemail.Text))
                    {
                        contactEmail = contactemail.Text.ToLower();
                    }
                    var aset = WORRddlasset.SelectedItem;
                    string asset = "";
                    string PriorityId = GlobalVariables.GetConfigValue(MWOSetupEnum.Priority__Default_Priority.ToString());
                    var emailContact = contactemail.Text;
    
                    string filter = "";
                    string AllowAssignment = GlobalVariables.GetConfigValue(MWOSetupEnum.General__Allow_Assignment.ToString());
                    if (!string.IsNullOrEmpty(AllowAssignment))
                    {
                        filter = AllowAssignment;
                    }
                    if (aset != null)
                    {
                        asset = (aset as Asset).Assettagnumber;
                    }
    
                    if (string.IsNullOrEmpty(status))
                    {
                        DisplayAlert("Message", "Status Required", "OK");
                    }
                    else if (string.IsNullOrEmpty(description))
                    {
                        DisplayAlert("Message", "Description Required", "OK");
                    }
                    else if (string.IsNullOrEmpty(location))
                    {
                        DisplayAlert("Message", "Please select Location", "OK");
                    }
                    else if (string.IsNullOrEmpty(roomNo))
                    {
                        DisplayAlert("Message", "Room Number Required", "OK");
                    }
                    else if (string.IsNullOrEmpty(asset))
                    {
                        DisplayAlert("Message", "Asset Required", "OK");
                    }
                    else if (string.IsNullOrEmpty(contact))
                    {
                        DisplayAlert("Message", "Contact Required", "OK");
                    }
                    else if (string.IsNullOrEmpty(contactEmail))
                    {
                        DisplayAlert("Message", "Contact Email Required", "OK");
                    }
                    else if (contactEmail != null)
                    {
                        var regEx = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";
                        if (!Regex.IsMatch(emailContact, regEx))
                        {
                            DisplayAlert("Message", "Email is not Valid", "OK");
                        }
                        else
                        {
                            if (GlobalVariables.IsNetworkConnect())
                            {
                                string url = GlobalVariables.ServiceUrl + "/CreateOrder/?username=" + GlobalVariables.UserName + "&password=" + GlobalVariables.Password + "&status=" + statusCode + "&locationid=" + location + "&WORRddlroom=" + roomNo + "&WORRddlcontact=" + contact + "&contactemail=" + contactEmail + "&WORRddlasset=" + asset + "&Description=" + description + "&createDate=" + createDate + "&priority=" + PriorityId + "&filter=" + filter;
                                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                                req.ContentType = "application/json";
                                req.Method = "GET";
                                req.BeginGetResponse(new AsyncCallback(CreateWORequest), req);
                            }
                        }
                    }
                    #endregion
            }
     private void CreateWORequest(IAsyncResult result)
            {
                try
                {
                    ValidateUser bsObj = new ValidateUser();
                    HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
                    using (Stream data = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        var ms = new MemoryStream(Encoding.Unicode.GetBytes(text));
                        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(WoOrders));
                        WoOrders bsObj2 = (WoOrders)deserializer.ReadObject(ms);
                        if (bsObj2.Status == 1)
                        {
                            GlobalVariables.remoteRequestPage = false;
                            string workOrderForMyCurrentLocation = GlobalVariables.GetConfigValue(MWOSetupEnum.General__Work_Orders_For_my_Current_Location.ToString());
                            string priorityWorkOrder = GlobalVariables.GetConfigValue(MWOSetupEnum.General__Priority_Work_Orders.ToString());
                            if (workOrderForMyCurrentLocation == "True")
                            {
                                initalizeRequest();
                            }
    
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                string Tmessage = "New Work Order Created Sucessfully";            // toast message
                                DependencyService.Get<IMessage>().LongAlert(Tmessage);  // toast message for show data save sucessfull
                                Navigation.PushModalAsync(new MasterWOPage(null));
    
                            });
    
                        }
                        else
                        {
                            Device.BeginInvokeOnMainThread(async () => await DisplayAlert("Message", "Data Save failed", "Ok"));
                        }
    
                    }
                }
                catch (Exception ex)
                {
                    ErrMsg.Text = ex.Message;
                }
    
            }
    
    I have a asset picker which have more than 10k data,so i think when i am binding this huge amount of data at that time app allocate more memory.
    
  • Xami3Xami3 ✭✭✭ PKMember, University ✭✭✭

    @Harshita and where is the xaml or listview c# code? what kind of strategy you are using?

  • HarshitaHarshita ✭✭✭✭ INMember ✭✭✭✭

    only I have a list view for Location and a asset picker,rest of the part contain simple entry fields.

     <Label x:Name="lblWORRddlasset" Text="Asset:" Margin="10,0,0,0" FontSize="Medium" TextColor="Black" />
                            <StackLayout Orientation="Horizontal">
                                <Picker x:Name="WORRddlasset" Title="Select a Asset Tag #" 
                                        ItemDisplayBinding="{Binding Assettagnumber}" IsEnabled="True" HorizontalOptions="FillAndExpand" Margin="10,0,0,0">
                                </Picker>
                                <ActivityIndicator Color="#6786C1" x:Name="AssetInd" IsRunning="True" IsVisible="True" Scale=".4"/>
    

    And here is the location list view implement by grid layout

    <StackLayout Padding="20" x:Name="NWOLocationStack" IsVisible="False" BackgroundColor="White" VerticalOptions="StartAndExpand" >
                    <StackLayout BackgroundColor="#e6f4ea" HeightRequest="450">
                        <Frame BackgroundColor="#6786C1" HeightRequest="50" Padding="0">
                            <Label Text="Select Location" HorizontalOptions="Center" VerticalOptions="Center" FontAttributes="Bold" FontSize="Medium" TextColor="White"/>
                        </Frame>
                        <StackLayout Padding="5">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition Height="*" />
                                </Grid.RowDefinitions>
                                <Label Text="Selected :" Grid.Row="0" Grid.Column="0" />
                                <Label x:Name="valselectedlocation" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" FontSize="Small"/>
                                <Entry x:Name="hdnLocation" IsVisible="False" Grid.Row="2" Grid.ColumnSpan="3"/>
                                <Entry x:Name="hdnPParentLocation" IsVisible="False" Grid.Row="3" Grid.ColumnSpan="3" />
                                <Button Clicked="BackLocation_Onclicked" Text="Back" Grid.Row="4" Grid.Column="0" BackgroundColor="#6786C1"/>
                                <Button Clicked="SubmitLocation_Onclicked" Text="Submit" Grid.Row="4" Grid.Column="1" BackgroundColor="#6786C1"/>
                                <Button Clicked="CancelLocation_Onclicked" Text="Cancel" Grid.Row="4" Grid.Column="2" BackgroundColor="#6786C1"/>
                                <StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand" Grid.Row="5" Grid.ColumnSpan="3">
                                    <ListView x:Name="LocationView" ItemSelected="OnSelectedItem">
                                        <ListView.ItemTemplate>
                                            <DataTemplate>
                                                <TextCell Text="{Binding locationName}" />
                                            </DataTemplate>
                                        </ListView.ItemTemplate>
                                    </ListView>
                                </StackLayout>
    
                            </Grid>
    
                        </StackLayout>
                    </StackLayout>
                </StackLayout>
    
  • Xami3Xami3 ✭✭✭ PKMember, University ✭✭✭

    @Harshita well picker are supposed to be used for short list of items, and i dont think that it is using any caching/virtualization support so if you are fetching 10k items may be it is causing it. the code looks fine to me.

    well you can debug it like.
    1. just assign first 10 items to picker and see if it is still crashing. (if crashes then something else is causing it)
    2. instead of Picker try to add a listview and set the cache strategy to recycle items (which will do vitualization).

  • CharwakaCharwaka ✭✭✭✭✭ INMember ✭✭✭✭✭
    edited February 2018

    Hi @Harshita

    Add ViewCell , CachingStrategy=RecycleElement, and listview Structure Should be like this

    https://us.v-cdn.net/5019960/uploads/editor/fd/3p7q2qc3wd9y.png

Sign In or Register to comment.