2012-03-11 80 views
1

我對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 
} 
+1

哪條線路導致NPE? – 2012-03-11 13:09:28

+0

FileInputStream fIn = openFileInput(「s [」+ i +「]。txt」); 此行導致NPE。 有沒有更好的方法來保存和加載對象數組?我正在使用FileOutputStream和FileInputStream。 – humanitarian570 2012-03-11 13:43:37

+0

你確定,有一個名爲「s [1] .txt」的文件,你正在尋找正確的文件夾? – stefan 2012-03-11 13:52:37

回答

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); 
} 
+0

afaik你是對的:'super'必須是構造函數中的第一個東西。 – stefan 2012-03-11 13:39:06

+0

我試過了,但沒有奏效。 NPE是由於FileInputStream,當調用方法a.loadData(s)時。 當沒有實例化Subject數組時,我有一個NPE,所以Subject數組不會拋出NPE。 – humanitarian570 2012-03-11 13:52:57

+0

你是怎麼調用這個方法的? 「a」是出勤的對象嗎? – Rikonator 2012-03-11 13:54:31

相關問題