Java Android:在异步任务中使用openFileOutput
我将学习本教程: 但是使用我自己的代码(不使用他们的twitter应用程序) 我似乎无法使openFileOutput正常工作,并尝试将其作为引用传递 我的类myList正在通过调用AsyncFetchDataJava Android:在异步任务中使用openFileOutput,java,android,android-asynctask,Java,Android,Android Asynctask,我将学习本教程: 但是使用我自己的代码(不使用他们的twitter应用程序) 我似乎无法使openFileOutput正常工作,并尝试将其作为引用传递 我的类myList正在通过调用AsyncFetchData new asynchfetchdata().execute(这个) 我正在尝试使用AsyncFetchData打开文件输出 fos = this.openFileOutput(TEA_CACHE_FILE, MODE_PRIVATE); 正如他们在教程中所说的那样。但是我不能让它工作。
new asynchfetchdata().execute(这个)代码>
我正在尝试使用AsyncFetchData打开文件输出
fos = this.openFileOutput(TEA_CACHE_FILE, MODE_PRIVATE);
正如他们在教程中所说的那样。但是我不能让它工作。至于代码的其余部分,我只是尝试创建一个包含虚拟数据的列表,等待是为了模拟网络调用的延迟。谢谢你的帮助,这是我的代码
公共类AsyncFetchData扩展了AsyncTask,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
}
private静态最终字符串TEA\u CACHE\u FILE=“TEA\u CACHE.ser”;
private List testea=new ArrayList();
@凌驾
受保护的Void doInBackground(列表…参数){
//当漫长的工作完成的时候{
//更新进度数据
//更新结果
//}
试一试{
睡眠(5000);
//创建虚拟茶列表
}
捕获(例外e){}
对于(int i=1;i您正在尝试从AsyncTask
调用openFileOutput
,它不是上下文
this.openFileOutput(...);
你应该
YourActivity.this.openFileOutput(...);
假设这是一个内部类,否则,this
引用的是您的AsyncTask
,而不是包含的活动