Reputation: 671
I am trying to read a .json file from the devices external directory.
I have a class called ExternalFile which is used to read in a file and return the contents as a string.
Here is the class:
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;
}
}
When i use this class to read a "login.json" file, it works fine. However when I use the class to read a "contacts.json" file, eclipse warns: "Null pointer access: The variable readJSON can only be null at this location".
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());
}
}
the only difference is that I pass in "contacts.json" instead of "login.json"
Upvotes: 0
Views: 139
Reputation: 17622
Eclipse warns if you are using a variable without intializing it. In your code, you have readJSON
declared but initialized to null
. Right after that its been used inside the try
block which will definitely cause NPE
ExternalFile readJSON = null; //--> you have not intialized readJSON
try
{
result = readJSON.readFile(REFERENCE_DIRECTORY, "contacts.json");
^^^^^^^^
null access here
Upvotes: 5