簡體   English   中英

Android:在AsyncTask中使用openFileOutput

[英]Android: using openFileOutput in an AsyncTask

我正在關注本教程: http : //www.codelearn.org/android-tutorial/twitter/10/asynctask-parameters-example

但是使用我自己的代碼(不使用他們的Twitter應用程序)

我似乎無法使openFileOutput正常工作,並嘗試結合使用此方法作為參考。

我的班myList通過調用AsyncFetchData

new AsyncFetchData().execute(this);

我正在嘗試使用以下命令在AsyncFetchData中打開文件輸出

fos = this.openFileOutput(TEA_CACHE_FILE, MODE_PRIVATE);

就像他們在教程中所說的那樣。 我不能使它正常工作。 至於其余的代碼,我只是試圖創建一個包含虛擬數據的列表,而等待是為了模擬網絡調用的延遲。 感謝您的幫助,這是我的代碼

公共類AsyncFetchData擴展了AsyncTask <List <TeaDetails>,Void,Void> {

private static final String TEA_CACHE_FILE = "tea_cache.ser";
private List<TeaDetails> tempTea = new ArrayList<TeaDetails>();

@Override
protected Void doInBackground(List < TeaDetails > ... params) {

    //while the long job getting done {
    //update progress_data
    //update result
   //}
    try {
        Thread.sleep(5000);
        // create dummy tea list
    }
    catch (Exception e){}
    for (int i=1; i<10; i++){
        TeaDetails tea = new TeaDetails();
        tea.setId("Id is: " + i);
        tea.setTitle("Title for tea number " + i);
        tea.setInfo("Some information about tea "+ i);
        tea.setImgSrc(i);
        tempTea.add(tea);
    }

    FileOutputStream fos;
    ObjectOutputStream oos;
    try {
        //code to write into file
        fos = this.openFileOutput(TEA_CACHE_FILE, MODE_PRIVATE);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(tempTea);
        // show in log that file was successfully written
        Log.d("HelloWorld2", "Successfully wrote teas to the file.");
        //close operators
        oos.close();
        fos.close();

    } catch (Exception e) {
        Log.e("HelloWorld2", "Error writing tweets", e);
    }
    return null;
}

protected void onProgressUpdate(Void... progress_data) {
    //use progress_data to show progress on the screen
}

protected void onPostExecute(Void... result) {
    //use result obtained at the end of
}

}

您正在嘗試從不是ContextAsyncTask調用openFileOutput 代替

this.openFileOutput(...);

你應該有

YourActivity.this.openFileOutput(...);

假設這是一個內部類,否則, this指向您的AsyncTask而不是封閉活動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM