I am trying to inherit a function from a class, but it returns NullPointerException
. Can anyone please help?
This is the function I try to inherit in Main.java
. This function operates well in Main.java
.
public void readData() {
String readString = "";
try {
FileInputStream fIn = openFileInput("user.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader buffreader = new BufferedReader(isr);
readString = buffreader.readLine();
isr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
telephonyManager.listen(myPhoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
Here is the coding in my another class:
Main main =new Main();
main.readData();
Error log:
04-16 02:58:23.812: E/AndroidRuntime(8125): java.lang.NullPointerException
04-16 02:58:23.812: E/AndroidRuntime(8125): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:167)
04-16 02:58:23.812: E/AndroidRuntime(8125): at com.test.Main.readData(Main.java:176)
The problem is that
openFileInput()
needs aContext
. You need to create a constructor in your class that takescontext
as aparam
.then pass your
Context
then use that when you call this function
Note You will want to use this
Context
if you have any other methods in this class that need itHere is an answer of mine on SO about the same thing