Как настроить отображение сообщения об ошибке в Android Xamarin? (Ищите, чтобы оно работало как txtError.Text = "Обнаружена ошибка") - PullRequest
0 голосов
/ 15 октября 2018

Я работаю над школьным проектом и получаю сообщение об исключении «Null Exception».В качестве поведения я хотел получить следующее: если я нажму кнопку «Сохранить» на экране «Добавить элемент», я получу сообщение о том, что оно прошло успешно или нет.Я попытался применить точки останова, но это просто дает мне то же самое сообщение.Мне сказали, что, скорее всего, код, указанный в комментарии, не работает, но я не уверен, что делать дальше.Ниже приведен мой код активности AddItem за

 protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.AddItem);

        FindViewById<Button>(Resource.Id.saveButton).Click += OnSaveClick;
        FindViewById<Button>(Resource.Id.cancelButton).Click += OnCancelClick;

        // Create your application here
    }

    void OnSaveClick(object sender, EventArgs e)
    {

        long countCheck;
        //Retrieve the values the uesr entered into the UI

        string name = FindViewById<EditText>(Resource.Id.nameInput).Text;
        int count = int.Parse(FindViewById<EditText>(Resource.Id.countInput).Text);

        var intent = new Intent();

        //Load the new data into an Intenet for transport back to the Activity that started this one.

        intent.PutExtra("ItemName", name);
        intent.PutExtra("ItemCount", count);

        //Send the resuylt code and dataaa back(this does not end the current Activity)



        SetResult(Result.Ok, intent);

        //End the current Activity
        Finish();

    }

    void OnCancelClick(object sender, EventArgs e)
    {
        //End the current Activity.
        //The Result Code will default to Result.Canceled.
        Finish();
    }

Это мой код MainActivity, за которым я пытался установить сообщение, но вместо этого выдается ошибка исключения.

public static List<Item> Items = new List<Item>();
    protected override void OnCreate(Bundle savedInstanceState)
    {
        //Pre-Load with some sample data for convenience.

        Items.Add(new Item("Milk", 2));
        Items.Add(new Item("Crackers", 1));
        Items.Add(new Item("Apples", 5));

        base.OnCreate(savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);

        FindViewById<Button>(Resource.Id.itemsButton).Click += OnItemsClick;
        FindViewById<Button>(Resource.Id.addItemButton).Click += OnAddItemClick;
        FindViewById<Button>(Resource.Id.aboutButton).Click += OnAboutClick;

    }
    void OnItemsClick(object sender, EventArgs e)
    {
        //User the standard technique to start an activity: create an Intent and then pas it to StartACtivity.
        var intent = new Intent(this, typeof(ItemsActivity));

        StartActivity(intent);
    }

    void OnAddItemClick(object sender, EventArgs e)
    {
        //The AddItem Activity will return the Name and Count of the newly added item.

        var intent = new Intent(this, typeof(AddItemActivity));

        //Use StartActivityForResult so you are notified when the AddItem Activity Completes.
        //The parameter '100' is the request code that lets you identify which Activity is sending your results;
        //The value '100' is arbitrary, it has no meaning to Android.
        StartActivityForResult(intent, 100);
    }
    void OnAboutClick(object sender, EventArgs e)
    {
        //Use the convenience method to start an Activity without creating an Intent.
        StartActivity(typeof(AboutActivity));
    }

    protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        //base.OnActivityResult(requestCode, resultCode, data);

        //A requestCode of 100 indicates this result is from the AddItem Activity.
        //The resultCode of OK means the user touched the SAVE button and not the CANCEL button.
        //The value for the new item are stored in the Intent Extras.
        if(requestCode == 100 && resultCode == Result.Ok)
        {
            string name = data.GetStringExtra("ItemName");
            int count = data.GetIntExtra("ItemCount", 0);
            long countCheck;
            //This adds the new item to the IItems,
            //public static List<Item> Items = new List<Item>();
            //Created as a global(public) variable at the top of this page.
            if(MainActivity.Items.Exists(x => x.Name == name))
            {
               // FindViewById<TextView>(Resource.Id.tvMessage).Text = "Item already exist in the list.";
            }


            else
            {
                MainActivity.Items.Add(new Item(name, count));
               // FindViewById<TextView>(Resource.Id.tvMessage).Text = "Item was added in the list.";
            }

        }
    }

1 Ответ

0 голосов
/ 16 октября 2018

Я использовал приведенный ниже код, и он работал.:)

Toast.MakeText (это, «Компания уже существует.», ToastLength.Long) .Show ();

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...