我正在尝试使用一个在我的应用程序中传递的简单对象类。首先,我用它来执行AsyncTask。在AsyncTask的const electron = require('electron')
const fs = require('fs')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const Menu = electron.Menu
const Tray = electron.Tray
const ipc = electron.ipcMain
const path = require('path')
const url = require('url')
const shell = electron.shell
let mainWindow
ipc.on('print-to-pdf', function (event) {
const pdfPath = path.join(__dirname, '/reports/print.pdf')
const win = BrowserWindow.fromWebContents(event.sender)
win.webContents.printToPDF({printBackground: true, landscape: true}, function (error, data) {
if (error) throw error
fs.writeFile(pdfPath, data, function (error) {
if (error) {
throw error
}
shell.openExternal('file://' + pdfPath)
event.sender.send('wrote-pdf', pdfPath)
})
})
})
方法中,我想让这个相同的对象类再次使用它的一些setter。如何将此onPostExecute
对象传递给AsyncTask的data
和doInBackground
?
代码:
TravelPlanner.java
onPostExecute
GetInfo.java
// Put departure & arrival into model class
data = new ReisData();
data.setDeparture(departureStation);
data.setArrival(arrivalStation);
// Start AsyncTask
GetInfo asyncTask = new GetInfo(this);
asyncTask.execute(data);
答案 0 :(得分:0)
您可以传递AsyncTask
TravelPlanner.java
// Put departure & arrival into model class
data = new ReisData();
data.setDeparture(departureStation);
data.setArrival(arrivalStation);
// Start AsyncTask
GetInfo asyncTask = new GetInfo(this,data); // here is
asyncTask.execute(data);
GetInfo.java
public class GetInfo extends AsyncTask<ReisData, Integer, String> {
ReisData data;
Reisplanner reisPlanner;
View view;
public GetInfo(Reisplanner main,ReisData data) {
this.data=data;// you can use this
this.reisPlanner = main;
view = reisPlanner.getView();
}
@Override
protected void onPreExecute() {
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
@Override
protected String doInBackground(ReisData... params) {
try {
// Return XML as string with route options
return HttpRequestHelper.downloadFromServer(params);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
DocumentBuilder builder;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(result)));
} catch (Exception e) {
e.printStackTrace();
}
// TODO: Get 'ReisData' object
if (doc != null) {
XMLParser.parse(doc);
}
// Start Reisadvies with ReisData class
Fragment fragment = new Reisadvies();
// TODO: Put ReisData class into Bundle
this.reisPlanner.startFragment(fragment);
}