Reputation: 433
I am trying to call this function form inside a service class that I have created. I am having some issues with the context required to get this function to work. It is to my knowledge that if we are working with context inside
of a service that the method getBaseContext()
should do, but for some reason this method is giving me a null pointer exception. This is the code that I am using for the file reader method. I will include the exception as well.
Some of the things that I have tried are withing the regards of changing getBaseContext()
to getApplicationContext()
but I am not getting any results. How do we manipulate context when inside of a service?
File reader code:
public String fileReader(Context context, String fileName) throws IOException, JSONException {
FileInputStream fis = getBaseContext().openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader streamReader = new BufferedReader(isr);
StringBuilder responseStrBuilder = new StringBuilder();
String inputString;
while((inputString = streamReader.readLine()) != null) {
responseStrBuilder.append(inputString);
}
streamReader.close();
isr.close();
fis.close();
return responseStrBuilder.toString();
}
The exception:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileInputStream android.content.Context.openFileInput(java.lang.String)' on a null object reference
W/System.err: at com.example.allwaystrack01.internalhtml_chat_demo.services.SystemWebService.fileReader(SystemWebService.java:115)
W/System.err: at com.example.allwaystrack01.internalhtml_chat_demo.services.SystemWebService$WebAppInterface.returnContent(SystemWebService.java:176)
W/System.err: at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
W/System.err: at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:39)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.os.HandlerThread.run(HandlerThread.java:61)
As a side note, this method works when being called from an actual activity. But not from within the service. Any particular reasoning behind this?
I would appreciate pointers.
Upvotes: 0
Views: 979
Reputation: 6403
A Service is a context, so you should be able to do:
openFileInput(fileName);
Without the getBaseContext or getApplicationContext.
If the class extends Service. That would at least not throw an NPE on the context.
But it might be that you are reading the file from the wrong method, for example onBind and not in the constructor?
Also, make sure you have the permission for that file that you are trying to read, since on Android 6.0 you need the permission to access external files.
Also, make sure that the string filename is not null when calling the method.
Upvotes: 4