2013-08-01 34 views
0

我試圖從設備外部目錄中讀取.json文件。不一致的空指針異常

我有一個名爲ExternalFile的類,它用於讀取文件並以字符串形式返回內容。

這裏是類:

public class ExternalFile 
{ 
final String EXTERNAL_STORAGE = Evironment.getExternalStorageDirectory().toString(); 
final String FIRSTDROID_DIRECTORY = EXTERNAL_STORAGE + "/firstdroid/"; 
final String SALES_DIRECTORY = FIRSTDROID_DIRECTORY + "sales/"; 
final String REFERENCE_DIRECTORY = FIRSTDROID_DIRECTORY + "reference/"; 

public String readFile(String direcectory, String fileName) 
{ 
    BufferedReader br; 
    StringBuilder sBuffer; 
    File JSON; 
    String line; 
    String retVal = null; 

    try 
    { 
     sBuffer = new StringBuilder(); 
     JSON = new File(direcectory, fileName); 

     br = new BufferedReader(new FileReader(JSON)); 
     while ((line = br.readLine()) != null) 
     { 
      sBuffer.append(line); 
      sBuffer.append('\n'); 
     } 

     retVal = sBuffer.toString(); 

     Log.d("File Results: ", retVal); 
    } 
    catch (Exception e) 
    { 
     Log.e("readJSON", e.getMessage()); 
    } 

    return retVal; 
} 

}

當我使用這個類來讀取 「login.json」 的文件,它工作正常。但是,當我使用該類來讀取「contacts.json」文件時,eclipse警告: 「空指針訪問:變量readJSON在此位置只能爲null」。

private void getContactNames() 
{ 
    // File jsonCustomers; 
    // BufferedReader br= null; 
    // StringBuilder sb = null; 
    // String line; 
    String result; 

    ExternalFile readJSON = null; 

    try 
    { 
      result = readJSON.readFile(REFERENCE_DIRECTORY, "contacts.json"); 

     // pass through the json string 
     readNames(result, "contact"); 
    } 
    catch (Exception e) 
    { 
     messageBox("getCustomerNames", e.toString()); 
    } 
} 

唯一的區別是,我通過在「contacts.json」而不是「login.json」

回答

5

Eclipse的,如果你使用的是變量沒有intializing它警告。在您的代碼中,您已聲明readJSON,但已初始化爲null。之後它被用在try區塊內,這肯定會導致NPE

ExternalFile readJSON = null; //--> you have not intialized readJSON 
try 
{ 
    result = readJSON.readFile(REFERENCE_DIRECTORY, "contacts.json"); 
       ^^^^^^^^ 
       null access here