BufferedReader不读取文件

时间:2017-12-01 17:55:11

标签: android bufferedreader

我在android studio中有一个应用程序的代码,我试图从文件中读取登录信息,但BufferedReader没有执行任何事情。

注册和登录页面都打开了,应用程序的第一页我有一个登录按钮和一个注册按钮,当我点击登录按钮时没有发生,甚至没有检查用户是否存在

我尝试了很多方法来读取和写入文件,但我无法弄清楚错误

它不是在阅读任何东西而不是写任何东西,它根本就什么都不做。

这是登录页面

package com.example.admin.projectfinal;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.admin.projectfinal.val.inputValidation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;


public class LoginActivity extends AppCompatActivity {

    private inputValidation InputValidation;

    private TextInputLayout IDLayout;
    private TextInputLayout PASSWORDlayout;
    private TextInputEditText LogID;
    private TextInputEditText PASS;
    Button SI;
    TextView TV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getSupportActionBar().hide();

        PASS = findViewById(R.id.password);
        LogID = findViewById(R.id.idd);

        IDLayout = findViewById(R.id.IDLayout);
        PASSWORDlayout = findViewById(R.id.PasswordLayout);
        TV = findViewById(R.id.tv);
        SI = findViewById(R.id.signin);


        SI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    login();

            }
        });

        TV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Navigate to RegisterActivity
                Toast.makeText(LoginActivity.this, "we are in tv.", Toast.LENGTH_LONG).show();

                Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intentRegister);
            }
        });
        InputValidation = new inputValidation(LoginActivity.this);

    }


    private void login() {

        if (!InputValidation.isInputEditTextFilled(LogID, IDLayout, "ID not filled ")) return;
        if (!InputValidation.isInputEditTextFilled(PASS, PASSWORDlayout, "Password not filled"))
            return;

            TextView FileContentTextView = findViewById(R.id.tv_file_content);


        try {
            File f = new File ("User.txt");
            BufferedReader reader = new BufferedReader(new FileReader(f));

            if (reader.ready()) {
                FileContentTextView.setText("No User registered");
                return;
            } else {
                Toast.makeText(LoginActivity.this, "else", Toast.LENGTH_LONG).show();

                boolean found = false;
                String role = null;
                String line;

                while ((line = reader.readLine()) != null) {
                    Toast.makeText(LoginActivity.this, "while", Toast.LENGTH_LONG).show();

                    StringTokenizer user = new StringTokenizer(line);
                    String name = user.nextToken();
                    String Id = user.nextToken();
                    String dob = user.nextToken();
                    String pas = user.nextToken();
                    String Campus = user.nextToken();
                    String gender = user.nextToken();
                    role = user.nextToken();

                    if (LogID.equals(Id)) {
                        Toast.makeText(LoginActivity.this, "id is good", Toast.LENGTH_LONG).show();
                        if (PASS.equals(pas)) {
                            Toast.makeText(LoginActivity.this, "pass good", Toast.LENGTH_LONG).show();
                            found = true;
                            break;
                        }
                    }
                    if (found) {
                        Toast.makeText(LoginActivity.this, "break.", Toast.LENGTH_LONG).show();
                        break;
                    }
                }
                if (found) {
                    Toast.makeText(LoginActivity.this, "found", Toast.LENGTH_LONG).show();

                    if (role.equals("Security")) {
                        Intent accountsIntent = new Intent(LoginActivity.this, SecurityPage.class);
                        accountsIntent.putExtra("ID", LogID.getText().toString().trim());
                    } else {
                        Intent accountsIntent = new Intent(LoginActivity.this, StudentPage.class);
                        accountsIntent.putExtra("ID", LogID.getText().toString().trim());
                    }
                } else
                    reader.close();
            }

        }catch(IOException e){

            e.printStackTrace();

        }
    }

}

这是注册码,它在BufferedReader没有执行的任何事情都有同样的问题。

    package com.example.admin.projectfinal;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.admin.projectfinal.val.inputValidation;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{

    private TextInputLayout textInputLayoutName;
    private TextInputLayout textInputLayoutId;
    private TextInputLayout textInputLayoutPassword;
    private TextInputLayout textInputLayoutDate;

    TextInputEditText Name;
    TextInputEditText id;
    TextInputEditText Password;
    TextInputEditText DOB;

    Spinner campus;
    Spinner Role;
    Spinner Gender;

    Button btn;
    Button Cancel;

    private inputValidation InputValidation;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        Name      = findViewById(R.id.name);
        id        = findViewById(R.id.ID);
        Password  = findViewById(R.id.password);
        DOB       = findViewById(R.id.dob);
        btn       = findViewById(R.id.next);
        Cancel    = findViewById(R.id.cancel);
        campus    = findViewById(R.id.campus);
        Gender    = findViewById(R.id.gender);
        Role      = findViewById(R.id.role);
        textInputLayoutName = findViewById(R.id.NameLayout);
        textInputLayoutId = findViewById(R.id.IdLayout);
        textInputLayoutPassword = findViewById(R.id.PasswordLayout);
        textInputLayoutDate = findViewById(R.id.DOBLayout);

        //list for campus
        String[] CampusList = new String[]{"MainCampus", "SasAlNakhlCampus", "MasdarCampus"};
        ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, CampusList);
        campus.setAdapter(adapter1);
        //list for gender
        String[] gen = new String[]{"Male", "Female"};
        ArrayAdapter<String> genAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, gen);
        Gender.setAdapter(genAdapter);
        //list for role
        String[] rolee = new String[]{"Student", "Security"};
        ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, rolee);
        Role.setAdapter(roleAdapter);
        // Buttons validation
        btn.setOnClickListener(this);
        Cancel.setOnClickListener(this);
        InputValidation = new inputValidation(RegisterActivity.this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.next:
                try {
                    validate();
                } catch (IOException e) {
                    Log.e("Exception", "File write failed: " + e.toString());
                }

                break;
            case R.id.cancel:
                // Navigate to RegisterActivity
                Intent intentRegister = new Intent(this, LoginActivity.class);
                startActivity(intentRegister);
                break;
        }
    }

    private void validate() throws IOException {

        boolean filled = true;
        if (!InputValidation.isInputEditTextFilled(Name, textInputLayoutName, "Fill Name")) {
            filled = false;
            return;
        }
        if (!InputValidation.isInputEditTextFilled(id, textInputLayoutId, "Fill ID")) {
            filled = false;
            return;
        }
        if (!InputValidation.isInputEditTextFilled(DOB, textInputLayoutDate, "Fill Date")) {
            filled = false;
            return;
        }
        if (!InputValidation.isInputEditTextFilled(Password, textInputLayoutPassword, "Invalid Password")) {
            filled = false;
            return;
        }

        if (filled){

            //if (!UserInfo.exists()) UserInfo.createNewFile();


            String line;
            boolean found = false;

                BufferedReader reader= new BufferedReader(new FileReader("User.txt"));
            Toast.makeText(getBaseContext(), "ready", Toast.LENGTH_LONG).show();

                while ((line = reader.readLine()) != null) {
                    Toast.makeText(getBaseContext(), "while", Toast.LENGTH_LONG).show();

                    String[] user = line.split(" ");
                    String name = user[0];
                    String Id = user[1];
                    String dob = user[2];
                    String password = user[3];
                    String Campus = user[4];
                    String gender = user[5];
                    String role = user[6];

                    if (id.equals(Id)) {
                        found = true;
                        Toast.makeText(getBaseContext(), "User Exist", Toast.LENGTH_LONG).show();
                        break;
                        }

                    if (!found) {
                        // Adds a line to the file
                        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("User.txt")));
                        writer.append(Name + " " + id + " " + DOB + " " + Password + " "
                                + campus.getSelectedItem() + " " + Gender.getSelectedItem() + " " + Role.getSelectedItem() + "/n" );
                    }
                }
                reader.close();



        }
    }
}

我在代码中使用的输入验证类:

package com.example.admin.projectfinal.val;

import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;


public class inputValidation {
    private static Context context;

    /**
     * constructor
     *
     * @param context
     */
    public inputValidation(Context context) {
        this.context = context;
    }

    /**
     * method to check InputEditText filled .
     *
     * @param textInputEditText
     * @param textInputLayout
     * @param message
     * @return
     */
    public static boolean isInputEditTextFilled(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message) {
        String value = textInputEditText.getText().toString().trim();
        if (value.isEmpty()) {
            textInputLayout.setError(message);
            hideKeyboardFrom(textInputEditText);
            return false;
        } else {
            textInputLayout.setErrorEnabled(false);
        }

        return true;
    }

    /**
     * method to Hide keyboard
     *
     * @param view
     */
    private static void hideKeyboardFrom(View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

0 个答案:

没有答案