将EditText与C#中的字符串进行比较

本文关键字:字符串 比较 EditText | 更新日期: 2023-09-27 18:21:04

我是C#和Android开发(使用Xamarin)的新手。我正在尝试创建一个简单的登录屏幕,它将检查用户输入,如果用户输入与文本文件中的数据匹配,它将显示登录成功,反之则显示登录失败。

我不得不提的是,我已经为此挣扎了将近一天。我觉得我在编码方面搞砸了,所以我创建了一个简单的控制台应用程序,在那里复制了代码,它运行得很好,所以我认为我的问题与比较字符串和EditText中的用户输入有关。

应用程序构建成功,但每次我按下下面显示的方法相关的按钮时,我的应用程序都会崩溃并把我赶出去。

我创建了两个名为user.txt和pass.txt的文本文件。pass.txt中的第一行是user.txt中第一行用户的密码。

再一次,我必须提到的是,代码在控制台应用程序中运行得很好(我用简单的console.Readline替换了EditText中的user_input,用console.Writeline替换了Toast.MakeText)。请问,我做错了什么?

    public void read_list(object sender, EventArgs e)
    {
        k = FindViewById<EditText>(Resource.Id.user);
        z = FindViewById<EditText>(Resource.Id.pass);
        string user_input = k.Text.ToString();
        string pass_input = z.Text.ToString();
        int count = 0;
        bool valid = false;
        const string person = "user.txt";
        List<string> users = new List<string>();
        using (StreamReader username = new StreamReader(person))
        {
            string line;
            while ((line = username.ReadLine()) != null)
            {
                users.Add(line);
            }
            foreach (string s in users)
            {
                if (Equals(s, user_input))
                {
                    valid = true;
                    break;
                }
                count++;
            }
        }

        const string key = "pass.txt";
        List<string> passwords = new List<string>();
        bool pass_valid = false;
        using (StreamReader password = new StreamReader(key))
        {
            string pass_line;
            while ((pass_line = password.ReadLine()) != null)
            {
                passwords.Add(pass_line);
            }
            if (Equals(passwords[count], pass_input))
            {
                pass_valid = true;
            }
            else
            {
                pass_valid = false;
            }
        }
        if ((pass_valid) && (valid))
        {
            Toast.MakeText(this, "Login successful", ToastLength.Short).Show();
        }
        else
        {
            Toast.MakeText(this, "Login failed", ToastLength.Short).Show();
        }

    }

将EditText与C#中的字符串进行比较

正如我所说,您的主要概念是错误的。让我们看看我的例子,看看这个:
主活动看起来像

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.IO;
namespace TestStuff
{
    [Activity(Label = "Main",MainLauncher=true,Icon = "@drawable/icon")]            
    public class MainActivity : Activity
    {
        //path of folder,where we want to save our .txt File(Downloads)
        Java.IO.File FolderToSave = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Second);
            EditText login = FindViewById<EditText>(Resource.Id.editText1);
            EditText password = FindViewById<EditText>(Resource.Id.editText2);
            Button btn = FindViewById<Button>(Resource.Id.btn);
            //here is final Path of our Credentials.txt
            string filePath = System.IO.Path.Combine(FolderToSave.Path, "Credentials.txt");
            //method,that will write correct login/password to .txt file
            this.WriteFile("Vasya", "12345",filePath);
            //eventhandler,when we pressing the button,method "check credentials will do some stuff
            btn.Click += (sender, e) => 
                {
                  //put parametrs: location of Credentials.txt and    current login and password
  CheckForCredentials(filePath,login.Text,password.Text);
                    };
        }
        //create and write credentials.txt with login and pass
        void WriteFile(string Login,string Password,string Path)
        {
            using (StreamWriter Credentials = new StreamWriter (Path))
            {
                //first row will be our login
                Credentials.WriteLine(Login);
                //second is password
                Credentials.WriteLine(Password);
            }
        }
        //check for correct data
        void CheckForCredentials(string Path,string CurrentLogin,string CurrentPassword)
        {
            string Login, Password;
            if (File.Exists(Path))
            {
                //reading from Credentials.txt first rows(that is our login)
                Login = File.ReadLines(Path).First();
                //same for password
                Password = File.ReadLines(Path).Last();
                //check if introduced values are correct!
                if (Login == CurrentLogin && Password == CurrentPassword)
                {
                    Toast.MakeText(this, "Credentials are correct", ToastLength.Short).Show();
                }
                else
                {
                    Toast.MakeText(this, "Something going wrong", ToastLength.Short).Show();
                }
            }
            else
            {
                //credentials for some reason doest exist in your app.
                Toast.MakeText(this, "Not exist file", ToastLength.Short).Show();
            }
        }
    }
}

MainLayout.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText1"
            android:layout_centerInParent="true"
            android:layout_marginLeft="60dp"
            android:hint="UserName" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/editText1"
            android:id="@+id/editText2"
            android:layout_centerInParent="true"
            android:layout_marginLeft="60dp"
            android:hint="Password" />
        <Button
            android:text="Check Credentials"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/editText2"
            android:id="@+id/btn"
            android:layout_centerInParent="true"
            android:layout_marginTop="20dp" />
    </RelativeLayout>
</LinearLayout> 

此外,您需要将权限放入AndroidManifest.xml(位于Propreties文件夹中)this:

  1. 写入外部存储
  2. ReadExternalStorage

仅此而已:)。