gpt4 book ai didi

java - BufferedReader 在 Android 应用程序中返回 null,但在 Java 应用程序中不返回 null

转载 作者:行者123 更新时间:2023-12-01 05:32:48 24 4
gpt4 key购买 nike

我已经用 Java 编写了一个应用程序,现在正尝试将其移植到 Android,但由于某种原因,当使用 BufferedReader 中的 readLine() 方法时,它返回 null。我已经用Java测试了代码,它工作得很好,没有问题。我正在读取的文件是一个纯文本文件,我已将其与其余的 java 文件一起放入。我的代码简单地接受用户输入的登录信息,然后单击登录按钮,通过读取包含配置文件的文本文件来检查详细信息。以下是我的代码的简化:

主 Activity 中的OnClickListener:

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText textUsername = (EditText) findViewById(R.id.textUsername);
EditText textPassword = (EditText) findViewById(R.id.textPassword);

// Collect the login details entered by the user
String username = textUsername.getText().toString();
String password = textPassword.getText().toString();

// Check if login details are correct
LoginModel login = new LoginModel();
Correct = login.isCorrect(username, password); // LINE COMMENTED
// OUT SO THAT DETAILS DON'T NEED TO BE ENTERED

// Correct = true; // used to bypass login for now
if (Correct) { // if details are correct then start main program
Intent intent = new Intent (LoginView.this, MenuListView.class);
startActivity(intent);
}
else System.out.println("Login is incorrect...");

}
});
}

LoginModel.java 类:

public LoginModel() {
file = new File("Profiles");
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Login Constructor successful!");
}

// Checks whether the inputted details are correct
public static boolean isCorrect(String u, String p) {
System.out.println(p);
boolean check = false;
String line = null;
try {
do {
line = br.readLine(); // This line is returning null
// System.out.println("Checking profile : " + line);
String[] info = line.split("\t");
// nested if-statement to improve efficiency over &&
if (info[0].equals(u)) {
System.out.println("username found!");
if (info[1].equals(p)) {
System.out.println("password correct!");
check = true;
} else
System.out.println("password incorrect!");
} else
System.out.println("username not found!");
} while (line != null && check == false);
return check;

br.readLine() 由于某种原因返回 null。我查了一下,bufferedreader 似乎完全支持。

编辑:好的,我发现它实际上并没有找到该文件,但可能试图执行 isCorrect() 方法,因为它是静态的。我现在已经删除了 method 和 br 声明静态标记,并将配置文件文本文件移动到包含所有 java 文件的文件夹中,但仍然找不到它。我应该如何引用该职位?如果我只是通过名称引用它,Android 查找该文件的默认位置是什么?非常感谢!

最佳答案

我不确定这是否是 NPE 的实际原因,但它肯定是一个错误:

您正在构造函数中初始化 br,但您在静态的 isCorrect() 中使用它!它不需要调用 oreder 中的 LoginModel 封闭类,因此在使用 br 之前可能根本不会调用 c'tor。

您应该在声明时或在静态作用域中初始化br,以便在类加载时初始化它。

编辑:请注意,它还表明 br 被声明为静态 - 因此 LogicModel 的所有实例实际上都使用 的相同对象>br!
br.readLine() 返回 null 的原因 - 可能是您已经在对 isCorrect() 的其他调用中耗尽了该文件,或者使用其他方法br,但如果没有更多代码,就不可能确定它。

关于java - BufferedReader 在 Android 应用程序中返回 null,但在 Java 应用程序中不返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com