Suppose you have this code
SampleActivity
Context context;
@Override 
protected void onCreate(Bundle savedInstanceState){
   super.onCreate(savedInstanceState);
   setContantView(R.layout.sample);
   context = getApplicationContext();
   new AsyncTask().execute();
}
public void fileWrite(){
   try{
       openFileOutput("fileName",Context.MODE_APPEND);
   }
}
AsyncTask
@Override 
protected void onPostExecute(String s){
   super.onPostExecute(s);
   SampleActivity sampleA = new SampleActivity();
   sampleA.fileWrite();
}
With this
FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
I get an error.
Since context is not generated when the instance is created in the code, it becomes NullPointerExeption.
If you want to avoid it> https://qiita.com/old_cat/items/ff4f2116192fd536fb59 As described in, implement the callback method and handle the context.
SampleActivity
Context context;
@Override 
protected void onCreate(Bundle savedInstanceState){
   super.onCreate(savedInstanceState);
   setContantView(R.layout.sample);
   context = getApplicationContext();
   AsyncTaskCallBack asyncTaskCallBack = new AsyncTaskCallBack();
   AsyncTask asyncTask = new AsyncTask(asyncTaskCallBack);
}
public class AsyncTaskCallBack(){
   //You can also use fileOutputStream here
   //But try calling another method
   public void one(){
      fileWriter();
   }
}
public void fileWrite(){
   try{
       openFileOutput("fileName",Context.MODE_APPEND);
   }
}
AsyncTask
SampleActivity.AsyncTaskCallBack asyncTaskCallBack;
public AsyncTask(SampleActivity.AsyncTaskCallBack asyncTaskCallBack){
   this.asyncTaskCallBack = asyncTaskCallBack;
}
@Override 
protected void onPostExecute(String s){
   super.onPostExecute(s);
   asyncTaskCallBack.one();
}
        Recommended Posts