Lewiky
Lewiky

Reputation: 325

The first app I have ever written crashes and I don't know why

I've started using Xamarin to program android apps in C#, but my app crashes before it even does anything. Can anyone identify why?

The purpose of the app is to simply take a quadratic equation in the form ax^2+bx+c and find it's two solutions and then display those solutions.

Thanks.

[Activity (Label = "FirstApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    int a = 4;
    int b = 1 ;
    int c = 2;
    int d;
    int s1;
    int s2;
    string fail ="There are no real roots!";


    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button> (Resource.Id.myButton);
        TextView sol2 = FindViewById<TextView> (Resource.Id.Solution2);
        TextView sol1 = FindViewById<TextView> (Resource.Id.Solution1);

        button.Click += delegate {
            quadratic(a,b,c);

            sol1.Text = string.Format (Convert.ToString(s1));

            sol2.Text = string.Format (Convert.ToString(s2));
        };

    }
    string quadratic (int a, int b, int c)
    {
        d = Convert.ToInt32(Math.Pow (b, 2)) - (4 * a * c);
        if (d < 0) {
            return(fail);
        } else{
            s1 = (-1 * b + Convert.ToInt32(Math.Sqrt (d))) / (2 * a);
            s2 = (-1 * b - Convert.ToInt32(Math.Sqrt (d))) / (2 * a);
            return(Convert.ToString(s1));
        }
    }
}

Upvotes: 1

Views: 93

Answers (2)

Lewiky
Lewiky

Reputation: 325

I found the solution! Simply put, I apparently had started developing my app for android API Level 22, and was trying to run it on a Level 21 emulator, so it wouldn't cope with it.

Downloading the Level 22 image and making a new emulator fixed the issue.

Upvotes: 0

MiCoDevelopers
MiCoDevelopers

Reputation: 21

I think the following lines are attempting to convert an undefined int to a string:

sol1.Text = string.Format (Convert.ToString(s1));
sol2.Text = string.Format (Convert.ToString(s2));

In my testing locally the project would not build until s1 and s2 had values.

int s1, s2 = -1;

Upvotes: 1

Related Questions