等待Listener完成任务并获得另一个函数的结果[Android]

时间:2016-03-25 08:42:38

标签: java android function

我想从我的文件浏览器函数中获取文件路径,但是我的文件浏览器函数有监听器,所以如果我在这个文件浏览器函数之后调用另一个函数,它会因为路径仍为空而崩溃,这里有两个函数我想打电话:

public void openFileExplorer() {
    File mPath = new File(Environment.getExternalStorageDirectory() + "/");
    fileDialog = new FileDialog(this, mPath);
    fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
        public void fileSelected(File file) {
            Log.d(getClass().getName(), "selected file " + file.toString());
            chosenFile = file.toString();
        }
    });
    fileDialog.showDialog();
}

private void generateMFCC(String path) {
   // btnBrowse.setText("Done");
    Log.d(getClass().getName(), ": Success");
    buffer = mRecorder.ReadWave(path);
    data = new float[buffer.length];

    for (int i = 0; i < buffer.length; i++) {
        data[i] = (float) buffer[i];
    }
    //Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
    preProcess = new PreProcess(data, samplePerFreame, sampleRate);
    featureExtract = new FeatureExtract(preProcess.framedSignal, sampleRate, samplePerFreame);
    featureExtract.makeMfccFeatureVector();
    featureVector = featureExtract.getFeatureVector();
    double[][] fv = featureVector.getMfccFeature();

    for (int i = 0; i < fv.length; i++) {
        test = test + "{" + "\n";
        for (int j = 0; j < fv[i].length; j++) {
            test = test + Double.toString(fv[i][j]) + ", ";
        }
        test = test + "}" + "\n";
    }}

我这样称呼函数:

openFileExplorer();
generateMFCC(chosenFile);

但它始终在文件资源管理器对话框打开之前出错

2 个答案:

答案 0 :(得分:0)

public void openFileExplorer() {
    File mPath = new File(Environment.getExternalStorageDirectory() + "/");
    fileDialog = new FileDialog(this, mPath);
    fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
        public void fileSelected(File file) {
            Log.d(getClass().getName(), "selected file " + file.toString());
            chosenFile = file.toString();
// you should call the function here
generateMFCC(chosenFile);
        }
    });
    fileDialog.showDialog();
}  

认为应该解决您的问题,现在调用generateMFCC(chosenFile);,无论选择何种文件 *在选择文件之前

答案 1 :(得分:0)

仅从openFileExplorer调用generateMFCC。

public void openFileExplorer() {
    File mPath = new File(Environment.getExternalStorageDirectory() + "/");
    fileDialog = new FileDialog(this, mPath);
    fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
        public void fileSelected(File file) {
            Log.d(getClass().getName(), "selected file " + file.toString());
            chosenFile = file.toString();
generateMFCC(chosenFile);

        }
    });
    fileDialog.showDialog();
}