【发布时间】:2022-11-19 00:39:56
【问题描述】:
我有一个 AsyncTask,它通过 sftp 从服务器获取一个 excel 文件。
public class DataAsyncTask extends AsyncTask<Void, InputStream, InputStream> {
ChannelSftp sftpChannel;
Session session = null;
InputStream inStream = null;
Context context;
private GetListener GetListener;
DataAsyncTask(Context ctx, GetListener listener) {
this.context = ctx;
this.GetListener = listener;
}
protected InputStream doInBackground(Void... params) {
String host = "xx.xx.xxx.xxx";
String user = "user";
String pass = "password";
int port = 22;
JSch jsch = new JSch();
try {
session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(pass);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp) channel;
inStream = sftpChannel.get("/Example/Data_test_v3.xls");
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
return inStream;
}
@Override
public void onPostExecute(InputStream myInputStream) {
GetListener.passInputStreamGet(myInputStream);
}
}
我想在另一个班级中使用这个 instream。我已经实现了一个获取输入流的接口类。
public interface GetListener {
void passInputStreamGet(InputStream interfaceInputStream);
}
If called in antoher class....
public class ListDataItems implements GetListener {
InputStream myInputStream;
HSSFWorkbook myWorkBook;
@Override
public void passInputStreamGet(InputStream interfaceInputStream) {
this.myInputStream = interfaceInputStream;
}
public LinkedHashMap<String, List<String>> getData() {
DataAsyncTask dataAsyncTask=new SleepAnalysisDataAsyncTask(mContext, ListDataItems.this);
dataAsyncTask.execute();
myWorkBook= new HSSFWorkbook(this.myInputStream);
}
}
I get the following error:
E/ListDataItems: error java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
任何人都可以帮助我,我不会再进一步了。 我试过同样的方法来通过 HSSFWorkbook,但没有成功。
如果我将以下代码放入 AsyncTask doInBackground,我可以读取 Inputstream,但如果我使用接口,则 inpustream 对象为空。
try {
myWorkBook = new HSSFWorkbook(inStream);
int sheetNum = myWorkBook.getNumberOfSheets();
HSSFSheet Sheet = myWorkBook.getSheetAt(0);
int Rows = Sheet.getLastRowNum();
int Columns = Sheet.getRow(1).getPhysicalNumberOfCells();
Log.d(TAG, "SFTP the num of sheets is " + sheetNum);
Log.d(TAG, "SFTP the name of sheet is " + Sheet.getSheetName());
Log.d(TAG, "SFTP total rows is row=" + Rows);
Log.d(TAG, "SFTP total cols is column=" + Columns);
} catch (IOException e) {
e.printStackTrace();
}
我刚刚又测试了一遍,我连onPostExecute里面的输入流都读不到。但为什么?
【问题讨论】:
-
从输入流中读取意味着互联网流量。所有的互联网通信都应该在一个线程中完成。在您的情况下,在 doInBackground 中。当 onPostExecute 运行时,该代码在主线程上执行:
NetWorkOnMainThreadException。你为什么不提这个例外? -
@bla 谢谢你的评论。我通过传递工作簿和对调用接口类进行一些更改来解决它。
-
如果您有解决方案,请将其作为答案发布以关闭问题。
标签: android interface android-asynctask sftp inputstream