Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

java - Calling method works fine the first time but raises a null after

I'm using a Natural Language Processing library OpenNLP on Android and first I have to link to a model, and I do that in the main method such as this, first I instantiate the object InputStream,

public static InputStream is;

Clearly it's going to be null for starters but that is why I initialize it as such in the onCreate class,

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

In my AsyncTask which is a custom class I then proceed in a method to refer the "R.raw.en" (which is a .bin file in my raw resources) into a SentenceModel method:

SentenceModel model = new SentenceModel(is);

And that is when the problem with the referencing occurs. The first time I run the code it works no problem, but it returns this error the second time when the app crashes:

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)

My complete AsyncTask:

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);
        }
    }
}

I tried the debugger, a break point at the line SentenceModel model = new SentenceModel(is); but no useful thing came out of it, the values seem to be existing as the first time:

first execution variables

the second time:

second execution variables

I attempted to move the methods to the MainActivity but more NullPointerExceptions come out. No close enough questions exist as I've been stuck for days. Appreciating any help!

question from:https://stackoverflow.com/questions/65944223/calling-method-works-fine-the-first-time-but-raises-a-null-after

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...