質問

I am trying to save html file. I have class which extends AsyncTask

public class DownloadBook extends AsyncTask<String, Void, String> {

Inside this class, I have this method:

private void writeFile(String result, String title) throws FileNotFoundException {
        FileOutputStream fos = openFileOutput(title+".html", MODE_PRIVATE);
        PrintWriter pw = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(fos)));
        pw.print(result);
        pw.close();
    }

MODE_PRIVATE is giving following error:

MODE_PRIVATE cannot be resolved to a variable

Then I changed it to Context.MODE_PRIVATE. Now openFileOutput is giving this error:

The method openFileOutput(String, int) is undefined for the type DownloadBook

How to solve this problem?

役に立ちましたか?

解決

Use Activity or Application context to call openFileOutput method from DownloadBook class as:

FileOutputStream fos = 
   getApplicationContext().openFileOutput( title+".html", Context.MODE_PRIVATE);

If DownloadBook is separate java class then use class constructor for getting Activity context for calling openFileOutput method as:

public class DownloadBook extends AsyncTask<String, Void, String> {
private Context context;

  public DownloadBook(Context context){
   this.context=context;
  }

}

Now use context for calling openFileOutput method :

FileOutputStream fos = 
   context.openFileOutput( title+".html", Context.MODE_PRIVATE);

From Activity pass context to DownloadBook class constructor :

DownloadBook obj_Downloadbook=new DownloadBook(getApplicationContext());
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top