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」