我對android編程非常陌生,但我在Java和C++方面有一些經驗。雖然我已經能夠完成很多程序,但我仍然在FileInputStream中使用NPE。 我正在嘗試創建一個考勤程序,用於跟蹤學生在講座中的出勤情況。以下是引發NPE的代碼:FileInputStream Android中的NullPointerException異常
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
}
哪條線路導致NPE? – 2012-03-11 13:09:28
FileInputStream fIn = openFileInput(「s [」+ i +「]。txt」); 此行導致NPE。 有沒有更好的方法來保存和加載對象數組?我正在使用FileOutputStream和FileInputStream。 – humanitarian570 2012-03-11 13:43:37
你確定,有一個名爲「s [1] .txt」的文件,你正在尋找正確的文件夾? – stefan 2012-03-11 13:52:37