Android中的FileInputStream NullPointerException

时间:2012-03-11 13:05:51

标签: android nullpointerexception fileinputstream

我对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
}

1 个答案:

答案 0 :(得分:1)

我假设您在访问Subject数组时遇到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);
}