Try/catch Not Working Inside A Custom Class, Npe
Fairly simple. I have a BIG class for my main project, and it became 'unwieldy'. SO today I decided to try making my own class, so I could simplify some of the code in the big cla
Solution 1:
I believe the problem is that you are trying to call this method
openFileInput()
without giving it context
which it needs. I still don't think you need to extend Activity
but make this a regular class by removing extends Activity
. Create an instance of this class when you need it in the calling Activity
like
DataHandler data = DataHandler (this); // give contextdata.retrieveData();
something like that to call the method. Then create a constructor in the class like
ublic classDataHandlerextendsActivity {
FileOutputStream file_out;
FileInputStream file_in;
ObjectOutputStream obj_out;
ObjectInputStream obj_in;
ArrayList<String> retrieved_data;
Context mContext; // add Context variablepublicDataHandler(Context context){
mContext = context; assign context
}
Then in your method use
publicArrayList<String> retrieveData(){
try {
file_in = mContext.openFileInput("array_saved");
obj_in = newObjectInputStream(obj_in);
if(obj_in.available() > 0){
retrieved_data = (ArrayList<String>) obj_in.readObject();
}
else{
retrieved_data = newArrayList<String>();
}
obj_in.close();
file_in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return retrieved_data;
}
I believe something like this should help. The method openFileInput()
is expecting a Context
which is null
at this point, hence the NPE
. Passing a Context
to the class will solve this problem as it will have the current Activity Context
Post a Comment for "Try/catch Not Working Inside A Custom Class, Npe"