【问题标题】:Android AsyncTask use openFileOutputStreamAndroid AsyncTask 使用 openFileOutputStream
【发布时间】:2013-08-26 21:24:12
【问题描述】:

我的 AsyncTask 中有错误。我尝试使用 FileOutputStream 将数据保存到文件中,因为我需要永久保存此数据。

所以我正在阅读本教程:Tutorial

但如果我将代码添加到我的 AsyncTask 中,我会收到此错误:

"方法 openFileOutputStream(String, int) 未定义类型 MainActivity.DownloadSpielplan"

DownloadSpielplan 是我的 AsyncTask

private class DownloadSpielplan extends AsyncTask <Void, Void, String>
    {
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub


            //dont wonder reverseString is created and filled i delete this part from the code for more readability


            FILENAME = "SpielTag";
            JOUR = reverseString;

            FileOutputStream fos = openFileOutputStream(FILENAME, Context.MODE_PRIVATE);
            fos.write(JOUR.getBytes());
            fos.close();


            return reverseString;
        }

        @Override
        protected void onPostExecute(String reverseString) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Download abgeschlossen!", Toast.LENGTH_LONG).show();
            super.onPostExecute(reverseString);
        }
    }   

我想问题是,我正在从 AsyncTask 调用 openFileOutputStream,但我找不到如何解决它的解决方案。 (因为我在 Android 中真的很新)

【问题讨论】:

  • 把你的logcat报错。
  • 它不是 logcat 错误,它是 eclipse 告诉我的错误,在这一行: FileOutputStream fos = openFileOutputStream(FILENAME, Context.MODE_PRIVATE); eclipse 告诉我:“方法 openFileOutputStream(String, int) 未定义 MainActivity.DownloadSpielplan 类型”
  • 你必须调用openFileOutput,你必须用活动上下文调用这个方法。 goo.gl/UWhN1m

标签: java android android-asynctask fileoutputstream


【解决方案1】:

方法名是openFileOutput,不是openFileOutputStream

打电话

MainActivity.this.openFileOutput(FILENAME, Context.MODE_PRIVATE)

而不是

openFileOutputStream(FILENAME, Context.MODE_PRIVATE)

在你的 doInBackground 方法中。

【讨论】:

    【解决方案2】:

    因为您试图从不是Activity 的类中访问方法openFileOutputStream。 相反,将您的代码编写为-

    FileOutputStream fos = MainActivity.this.openFileOutputStream(FILENAME, Context.MODE_PRIVATE);
    

    或者其他选项是从在其构造函数中调用DownloadSpielplan 的活动传递上下文,并使用上下文打开文件输出-

    FileOutputStream fos = context.openFileOutputStream(FILENAME, Context.MODE_PRIVATE);
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      相关资源
      最近更新 更多