简体   繁体   中英

Android: using openFileOutput in an AsyncTask

I am following this tutorial: http://www.codelearn.org/android-tutorial/twitter/10/asynctask-parameters-example

but using my own code (not doing their twitter app)

I can't seem to get openFileOutput working and have tried a combination of passing in this as a reference.

my class myList is calling AsyncFetchData through

new AsyncFetchData().execute(this);

and I'm trying to open the file output in AsyncFetchData with

fos = this.openFileOutput(TEA_CACHE_FILE, MODE_PRIVATE);

as they say to do in the tutorial. I cannot get it to work though. As for the rest of the code, I am just trying to create a list with dummy data and the wait is to simulate the delay from a network call. thanks for any help, here is my code

public class AsyncFetchData extends 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
}

}

You're trying call openFileOutput from an AsyncTask , which is not a Context . Instead of

this.openFileOutput(...);

you should have

YourActivity.this.openFileOutput(...);

assuming this is an inner class as otherwise the this refers to your AsyncTask and not the enclosing activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM