MODE_PRIVATE tidak dapat diselesaikan ke variabel di openFileOutput

Saya mencoba menyimpan file html. Saya memiliki kelas yang memperluas AsyncTask

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

Di dalam kelas ini, saya punya metode ini:

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 memberikan kesalahan berikut:

MODE_PRIVATE tidak dapat diselesaikan ke suatu variabel

Lalu saya mengubahnya menjadi Context.MODE_PRIVATE. Sekarang openFileOutput memberikan kesalahan ini:

Metode openFileOutput(String, int) tidak ditentukan untuk tipe DownloadBook

Bagaimana cara mengatasi masalah ini?


person user3388473    schedule 23.03.2014    source sumber


Jawaban (1)


Gunakan konteks Aktivitas atau Aplikasi untuk memanggil metode openFileOutput dari kelas DownloadBook sebagai:

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

Jika DownloadBook adalah kelas Java yang terpisah maka gunakan konstruktor kelas untuk mendapatkan konteks Aktivitas untuk memanggil metode openFileOutput sebagai:

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

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

}

Sekarang gunakan context untuk memanggil metode openFileOutput :

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

Dari konteks penyampaian Aktivitas ke konstruktor kelas DownloadBook :

DownloadBook obj_Downloadbook=new DownloadBook(getApplicationContext());
person ρяσѕρєя K    schedule 23.03.2014
comment
itu memberikan kesalahan: Metode getApplicationContext() tidak ditentukan untuk jenis DownloadBook - person user3388473; 23.03.2014
comment
@ user3388473 : apakah DownloadBook kelas java terpisah atau kelas dalam Aktivitas? - person ρяσѕρєя K; 23.03.2014