简体   繁体   中英

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.

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
$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.

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.

使用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(this.ApplicationContext)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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