Wednesday, August 28, 2013

Reading from assets gives null pointer

Reading from assets gives null pointer

I hava a file in the assets folder that i want to access in a class ive
named StorageManager (just a regular class, doesnt extend anything)
public class StorageManager {
private Context context;
public StorageManager(Context context){
this.context=context;
}
public String readFileAsString(String filePath) throws
java.io.IOException {
AssetManager am = context.getAssets();
InputStream is = am.open(filePath);
String results = "";
int data = is.read();
while (data !=-1) {
results += (char)data;
data = is.read();
}
is.close();
return results;
}
}
Im creating an instance of this class within a ListFragment and passing
getActivity() as the context
However when i make a call to readFileAsString with a valid filePath I get
a NullPointerException for the line:
AssetManager am = context.getAssets();
Im assuming that means the context is null. But why? How do I fix this?



EDIT
filePath = "url" (the file is saved wth no extension in the assets folder)
But it doesnt get to the line where that is required, the file is opened
after the NullPointerError
The constructor is called within a class that extends ListFragment:
StorageManager storage = new StorageManager(getActivity());

No comments:

Post a Comment