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

时间:2015-11-06 15:21:50

标签: c# android string xamarin android-edittext

我是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();
        }


    }

1 个答案:

答案 0 :(得分:0)

正如我所说,你的主要观念是错误的。让我们看看我的例子,看看这个:
MainActivity 看起来像

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 )中添加权限:

  1. WriteExternalStorage
  2. ReadExternalStorage
  3. 这就是全部:)。