简体   繁体   English

单击按钮时不会弹出吐司消息

[英]Toast message won't popup on button click

This is the code, all I want to do is to test if user credentials are entered in the database then display success via toast message if they are and if they are not to return an error message. 这是代码,我要做的就是测试是否在数据库中输入了用户凭据,然后通过Toast消息显示成功,如果它们成功,以及是否不返回错误消息。

Here is what I have found out from one of the websites I followed all the instructions and ended up with the code below but the toast still doesn't show up. 这是我在其中一个网站上找到的内容,我按照所有说明进行操作,最终显示以下代码,但吐司仍然没有出现。

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Views.InputMethods;
using Android.Content;
using Android.Views;
using System;
using System.Net;
using System.Collections.Specialized;
using Org.Json;
using System.Text;
namespace App
{
    [Activity(Label = "App", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity, Android.Views.View.IOnClickListener
    {
        EditText username, password;
        Button signIn;
        signInAsync sn;
        protected override void OnCreate(Bundle bundle)
        {

            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            initialize();
        }
        public void initialize()
        {
            username = (EditText)FindViewById(Resource.Id.editText1);
            password = (EditText)FindViewById(Resource.Id.editText2);
            signIn = (Button)FindViewById(Resource.Id.button1);
            signIn.SetOnClickListener(this);
        }
        public override bool OnTouchEvent(MotionEvent e)
        {
            InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
            EditText username = (EditText)FindViewById(Resource.Id.editText1);
            EditText password = (EditText)FindViewById(Resource.Id.editText2);
            //Cisti fokus
            username.ClearFocus();
            password.ClearFocus();
            //imm.HideSoftInputFromWindow(username.WindowToken, 0);
            return base.OnTouchEvent(e);
            //Sklanja tastaturu s ekrana na klik na pozadinu.
        }
        public void OnClick(View v)
        {
            switch (v.Id)
            {
                case Resource.Id.button1:
                    sn = new signInAsync(this);
                    sn.Execute();
                    break;
            }
        }
        public class signInAsync : AsyncTask
        {
            MainActivity mainActivity;

            public signInAsync(MainActivity mainActivity)
            {
                this.mainActivity = mainActivity;
            }
            string username, password;
            protected override void OnPreExecute()
            {
                base.OnPreExecute();

                username = mainActivity.username.Text;
                password = mainActivity.password.Text;
            }
            protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
            {

                WebClient client = new WebClient();
                client.UseDefaultCredentials = true;
                client.Proxy.Credentials = CredentialCache.DefaultCredentials;
                Uri uri = new Uri("http://192.168.1.198/android/login.php");
                NameValueCollection parameters = new NameValueCollection();
                parameters.Add("username", username);
                parameters.Add("password", password);
                var response = client.UploadValues(uri, parameters);
                var responseString = Encoding.UTF8.GetString(response);
                JSONObject ob = new JSONObject(responseString);
                if (ob.OptString("success").Equals("1"))
                {
                    mainActivity.RunOnUiThread(() =>
                    {
                        Toast.MakeText(mainActivity, "Uspješno ste se ulogovali", ToastLength.Short).Show();
                    });
                };
                if (ob.OptString("error").Equals("2"))
                    Toast.MakeText(mainActivity, "Pogresno", ToastLength.Short).Show();
                if (ob.OptString("error").Equals("3"))
                    Toast.MakeText(mainActivity, "Error", ToastLength.Short).Show();
                return null;
            }

        }
    }
}

Here is my PHP file: 这是我的PHP文件:

<?php
$db_name = "korisnici";
$mysql_username = "Mpro";
$mysql_password = "prolinet";
$server_name = "192.168.1.198";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);

if($conn) {
    echo "Connection success";
} else {
    echo "Faliure to connect";
}

if(isset($_POST['username']) && isset($_POST['password'])) {
    $user_name = $_POST['username'];
    $user_pass = $_POST['password'];
    $mysql_qry = "SELECT * FROM korisnici WHERE username = '$user_name' AND password = '$user_pass'";
    if(mysql_fetch_row($mysql_qry)){
        $response["success"] = 1;
        echo json_encode($response);

    } else{
        $response["error"]=2;
        echo json_encode($response);
    }

} else {
    $response["error"] = 3;
    echo json_encode($response);
}
?>

I am sorry to bother you but I am a Xamarin beginner. 很抱歉打扰您,但我是Xamarin初学者。

change this line 改变这条线

Toast.MakeText(mainActivity, "Uspješno ste se ulogovali", ToastLength.Short).Show();

with: 有:

Toast.MakeText(mainActivity.this, "Uspješno ste se ulogovali", ToastLength.Short).Show();

Hope it helps 希望能帮助到你

如果要在使用asyntask时显示成功或失败的烤面包,请在asynctask的onPostExcute()方法中使用烤面包。

first make sure the line for showing toast is executed. 首先,确保显示吐司的行已执行。 you can use Log class to print some message to ensure what is happening in your application. 您可以使用Log类来打印一些消息,以确保应用程序中发生了什么。

使用getContextmainActivity.this代替mainActivity

You cannot be sure that your activity is in a valid state from the background thread. 您不能从后台线程确定您的活动处于有效状态。 So rather than passing in the activity pass in the application context like so: 因此,与其像这样在应用程序上下文中传递活动传递,不如说:

public signInAsync(Context appContext)

And then do: 然后执行:

Toast.MakeText(appContext,...

So when you call signInAsync from an activity you will call it like this: 因此,当您从活动中调用signInAsync时,您将像这样调用它:

signInAsync(this.ApplicationContext)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM