调用方法第一次工作正常,但在

我在 Android 上使用自然语言处理库 OpenNLP,首先我必须链接到一个模型,我在主要方法中这样做,例如,首先我实例化对象 InputStream,

public static InputStream is;

显然,对于初学者来说,它将是 null,但这就是我在 onCreate 类中将其初始化的原因,

is = getResources().openRawResource(R.raw.en);

在我的自定义类 AsyncTask 中,然后我继续使用一种方法将“R.raw.en”(这是我的原始资源中的 .bin 文件)引用到 SentenceModel 方法中:

SentenceModel model = new SentenceModel(is);

这就是引用出现问题的时候。我第一次运行代码时它没有问题,但是当应用程序崩溃时它第二次返回这个错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.util.Properties.getProperty(java.lang.String)' on a null object reference
    at opennlp.tools.util.model.BaseModel.getManifestProperty(BaseModel.java:506)
    at opennlp.tools.util.model.BaseModel.initializeFactory(BaseModel.java:248)
    at opennlp.tools.util.model.BaseModel.loadmodel(BaseModel.java:234)
    at opennlp.tools.util.model.BaseModel.<init>(BaseModel.java:176)
    at opennlp.tools.sentdetect.SentenceModel.<init>(SentenceModel.java:92)
    at com.jwanhsulaiman.talktag.Post.sentenceDetect(Post.java:75)
    at com.jwanhsulaiman.talktag.Post.onPostExecute(Post.java:102)
    at com.jwanhsulaiman.talktag.Post.onPostExecute(Post.java:25)
    at android.os.AsyncTask.finish(AsyncTask.java:695)
    at android.os.AsyncTask.access$600(AsyncTask.java:180)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:280)
    at android.app.activityThread.main(activityThread.java:6706)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

我完整的异步任务:

package com.jwanhsulaiman.talktag;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import edu.stanford.nlp.tagger.maxent.MaxentTagger;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.util.InvalidFormatException;

import static com.jwanhsulaiman.talktag.Mainactivity.is;

public class Post extends AsyncTask<String,MaxentTagger,MaxentTagger> {

    @SuppressLint("StaticFieldLeak")
    private final EditText mEdtTxt;
    @SuppressLint("StaticFieldLeak")
    private final TextView mTxtMsg;
    private String text;
    @SuppressLint("StaticFieldLeak")
    private final Spinner spinner;

    private final List<String> senlist = new ArrayList<>();

    public Post(EditText mEdtTxt,TextView mTxtMsg,Spinner spinner) throws IOException {
        this.mEdtTxt = mEdtTxt;
        this.mTxtMsg = mTxtMsg;
        this.spinner = spinner;
    }

    public interface PostCallback{
        void onSuccess(String sample);
        void onError(Exception exception);

    }

    private PostCallback callback;
    private Exception exception;

    public void setPostCallback(PostCallback callback){
        this.callback = callback;
    }

    @Override
    protected MaxentTagger doInBackground(String... strings) {

        // Do something that takes a long time,for example:
        @SuppressLint("WrongThread") MaxentTagger tagger = new MaxentTagger(
                "edu/stanford/nlp/models/" + spinner.getSelectedItem().toString() + ".tagger");

        return tagger;
    }

    protected void onProgressUpdate(Integer... progress) {

    }

    public List<String> sentenceDetect(String trimmed) throws InvalidFormatException,IOException,URISyntaxException {
        String paragraph = trimmed;

        // refer to model file "en-sent,bin",available at link http://opennlp.sourceforge.net/models-1.5/
        // load the model
        SentenceModel model = new SentenceModel(is);

        SentenceDetectorME sdetector = new SentenceDetectorME(model);

        // detect sentences in the paragraph
        String[] sentences = sdetector.sentDetect(paragraph);

        // print the sentences detected,to console
        for(int i=0;i<sentences.length;i++){
            System.out.println(sentences[i]);
            senlist.add(sentences[i]);
            System.out.println(senlist);
        }
        return senlist;
    }

    @Override
    public void onPostExecute(MaxentTagger tagger){
        // Note: this will be executed on the main thread
        if(exception == null){
            callback.onSuccess(text);
            //System.out.println(jsonObject.toString());
            try {
                mEdtTxt.findViewById(R.id.editText);
                mTxtMsg.findViewById(R.id.message);
                String sample = mEdtTxt.getText().toString();
                String removedSpaces = sample.trim().replaceAll(" +"," ");
                List<String> sentences = new ArrayList<>(sentenceDetect(removedSpaces));
                for (int i = 0; i < sentences.size(); i++) {
                    String tagged = tagger.tagString(String.valueOf(sentences.get(i)));
                }
                //mTxtMsg.setText(tagged);



                String[] wordsInSent = removedSpaces.split("\\s+");
                for (int i = 0; i < wordsInSent.length; i++) {
                    // You may want to check for a non-word character before blindly
                    // performing a replacement
                    // It may also be necessary to adjust the character class
                    wordsInSent[i] = wordsInSent[i].replaceAll("[^\\w]","");
                }

/**
                StringTokenizer tokens = new StringTokenizer(tagged,"_");
                String first = tokens.nextToken();
                System.out.println(first);
                String second = tokens.nextToken();
                System.out.println(second);
**/
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } finally {
                System.out.println("Whoopa");
            }
        } else if (exception != null) {
            callback.onError(exception);
        }
    }
}

我尝试了调试器,在行 SentenceModel model = new SentenceModel(is); 处有一个断点,但没有产生任何有用的东西,这些值似乎是第一次存在:

调用方法第一次工作正常,但在

第二次:

调用方法第一次工作正常,但在

我尝试将方法移至 Mainactivity,但出现了更多 NullPointerExceptions。没有足够接近的问题存在,因为我已经被困了好几天了。感谢任何帮助!

zhangweiw 回答:调用方法第一次工作正常,但在

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/1021564.html

大家都在问