【问题标题】:FileInputStream NullPointerException in AndroidAndroid 中的 FileInputStream NullPointerException
【发布时间】:2012-03-11 13:05:50
【问题描述】:

我对 android 编程非常陌生,但我在 Java 和 C++ 方面有一些经验。虽然我已经能够完成大部分程序,但我在 FileInputStream 中遇到了 NPE。 我正在尝试创建一个出勤程序,该程序可以跟踪学生在讲座中的出勤情况。这是抛出 NPE 的代码:

    public class Attendance extends Activity {
Subject s[] = new Subject[13];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    for(int i=0;i<13;i++) {
        s[i] = new Subject();
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public void loadData(Subject s[]) throws IOException{
    for(int i=0;i<13;i++) {
        int a[] = new int [2];
        int x=0;
        try {
            FileInputStream fIn = openFileInput("s["+i+"].txt");
            InputStreamReader isr = new InputStreamReader(fIn); //NPE occurs here
            //char buff[] = new char[100];
            //isr.read(buff);
            BufferedReader br = new BufferedReader(isr);
            String str = new String();
            while ((str=br.readLine())!=null) {
                a[x]=Integer.parseInt(str);
                x++;
            }
            s[i].acceptAttd(a[0]);
            s[i].acceptLecs(a[1]);
        }
        catch(IOException e) {
            //do nothing.
        }
    }
}

public void addAttnd(View v) throws IOException{
    setContentView(R.layout.addattnd2);
    Attendance a = new Attendance();
    a.loadData(s); //this line calls the method containing FileInputStream
}

【问题讨论】:

  • FileInputStream fIn = openFileInput("s["+i+"].txt");这条线导致 NPE。有没有更好的方法来保存和加载对象数组?我正在使用 FileOutputStream 和 FileInputStream。
  • 您确定有一个名为“s[1].txt”的文件并且您正在查找正确的文件夹吗?
  • 实际上,我不知道如何检查文件是否已创建。但是,如果该文件尚未创建,它会抛出 FileNotFoundException,而不是 NPE,所以我不知道为什么它会给出 NPE。我用不同的方法创建了文件,我没有在这里展示,因为代码会太长。

标签: android nullpointerexception fileinputstream


【解决方案1】:

我假设您在访问主题数组时收到 NullPointerException。

我不保证它会起作用,但试试这个。在您的 onCreate() 中,调用 super.onCreate() 后实例化 Subject 对象。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    for(int i=0;i<13;i++) {
        s[i] = new Subject();
    }
    setContentView(R.layout.main);
}

【讨论】:

  • afaik 你是对的:super 必须是构造函数中的第一件事。
  • 我试过了,但是没有用。 NPE 是因为 FileInputStream,当方法 a.loadData(s) 被调用时。当没有 Subject 数组的实例化时,我有一个 NPE,所以 Subject 数组没有抛出 NPE。
  • 你是怎么调用这个方法的? a是考勤对象吗?
  • 是的,'a' 是出席的对象,我刚才把那个代码放在主要问题中。我必须这样做,因为如果我将 openFileInput() 方法放在静态方法中,它将无法工作,因此我需要创建 Attendance 类的对象。否则,对象“a”没有用处。
  • 据我所知,您不能像这样实例化活动。如果要启动 Activity,请使用 Intent。您必须更改调用此方法的方式。如果您根本不想启动出勤活动,则不需要出勤来延长活动。这一切都取决于您拥有哪些活动以及您计划如何使用它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多