Android:NullPointerException,应用程序崩溃

问题描述 投票:0回答:2

我使用的api将根据用户输入的文本返回音调列表,具体取决于文本,如果api可以从用户输入中检测到某些音调,则该应用程序将显示结果列表,但是, api有时会崩溃,我猜是因为它返回空结果?

我无法控制api服务器,我尝试通过检查列表的大小来避免此问题,如果列表为空或不是空的,但是没有用,则该应用程序仍然崩溃。

是否有防止应用崩溃的方法?我认为没有确定方法来检查用户输入是否会从api返回某些信息,这取决于该api本身。非常感谢您的帮助。

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ibm.cloud.sdk.core.security.IamAuthenticator;
import com.ibm.cloud.sdk.core.service.exception.NotFoundException;
import com.ibm.cloud.sdk.core.service.exception.RequestTooLargeException;
import com.ibm.cloud.sdk.core.service.exception.ServiceResponseException;
import com.ibm.watson.tone_analyzer.v3.ToneAnalyzer;
import com.ibm.watson.tone_analyzer.v3.model.SentenceAnalysis;
import com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis;
import com.ibm.watson.tone_analyzer.v3.model.ToneOptions;
import com.ibm.watson.tone_analyzer.v3.model.ToneScore;

import java.util.List;

public class Main2Activity extends AppCompatActivity {

    private TextView textmain1, textmain2;
    private EditText editText;
    private Button submitBtn;
    private ToneAnalysis toneAnalysis;

    private List<ToneScore> documentToneScores;
    private List<SentenceAnalysis> sentenceDetectedTones;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        textmain1 = (TextView) findViewById(R.id.textmain1);
        textmain2 = (TextView) findViewById(R.id.textmain2);
        editText = (EditText) findViewById(R.id.edittext);
        submitBtn = (Button) findViewById(R.id.submitBtn);

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int SDK_INT = android.os.Build.VERSION.SDK_INT;
                if (SDK_INT > 8) {
                    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);

                    String userInputText = editText.getText().toString();

                    try {
                        IamAuthenticator authenticator = new IamAuthenticator(authenticatorString);
                        ToneAnalyzer toneAnalyzer = new ToneAnalyzer("2020-02-22", authenticator);
                        toneAnalyzer.setServiceUrl(url);
                        ToneOptions toneOptions = new ToneOptions.Builder().text(userInputText).build();

                        toneAnalysis = toneAnalyzer.tone(toneOptions).execute().getResult();

                        documentToneScores = toneAnalysis.getDocumentTone().getTones();
                        int toneSizelist = documentToneScores.size();
                        if (toneSizelist == 0) {
                            Toast.makeText(Main2Activity.this, "No tones", Toast.LENGTH_SHORT).show();
                        } else {
                            StringBuilder detectedTones = new StringBuilder();
                            for (ToneScore score : documentToneScores) {
                                if (score.getScore() > 0.5f) {
                                    detectedTones.append(score.getToneName()).append(" \n").append(score.getScore()).append("\n\n");
                                }
                            }
                            textmain1.setText(detectedTones.toString());
                        }

                        sentenceDetectedTones = toneAnalysis.getSentencesTone();
                        int listSize = sentenceDetectedTones.size();
                        if (listSize == 0) {
                            Toast.makeText(Main2Activity.this, "Oops!", Toast.LENGTH_SHORT).show();
                        } else {
                            StringBuilder sentenceTones = new StringBuilder();

                            for (SentenceAnalysis sentenceAnalysis : sentenceDetectedTones) {

                                List<ToneScore> singleScoreBlock = sentenceAnalysis.getTones();

                                for (ToneScore toneScore : singleScoreBlock) {
                                    if (toneScore.getScore() > 0.5) {
                                        sentenceTones.append("\"" + sentenceAnalysis.getText() + "\"");
                                        sentenceTones.append("\n").append(toneScore.getToneName()).append(": ").append(toneScore.getScore()).append("\n\n");
                                    }
                                }
                            }
                            textmain2.setText(sentenceTones);
                        }
                    } catch (NotFoundException e) {
                        // Handle Not Found (404) exception
                        Toast.makeText(Main2Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                    } catch (RequestTooLargeException e) {
                        // Handle Request Too Large (413) exception
                    } catch (ServiceResponseException e) {
                        // Base class for all exceptions caused by error responses from the service
                        System.out.println("Service returned status code " + e.getStatusCode() + ": " + e.getMessage());
                    } catch (ArrayIndexOutOfBoundsException e){
                        Toast.makeText(Main2Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    editText.setText("");
                }
            }
        });
    }
}

由于返回结果为空而导致应用程序崩溃时,错误nullpointerexception

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.amethyst.toneanalyzer, PID: 3492
    java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
        at com.amethyst.toneanalyzer.Main2Activity$1.onClick(Main2Activity.java:82)
        at android.view.View.performClick(View.java:6724)
        at android.view.View.performClickInternal(View.java:6682)
        at android.view.View.access$3400(View.java:799)
        at android.view.View$PerformClick.run(View.java:26355)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:226)
        at android.app.ActivityThread.main(ActivityThread.java:7231)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:500)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:913)
I/Process: Sending signal. PID: 3492 SIG: 9

谢谢你。

java android ibm-watson tone-analyzer
2个回答
0
投票

这些方法中的一个或多个正在返回null

toneAnalysis.getDocumentTone()

toneAnalysis.getDocumentTone().getTones();

toneAnalysis.getSentencesTone();

您必须纠正它们


0
投票

java.lang。NullPointerException:尝试调用接口方法空对象引用上的'int java.util.List.size()'

应用程序应抛出此类的实例,以指示对null对象的其他非法使用。您应该初始化ArrayList

NullPointerException
© www.soinside.com 2019 - 2024. All rights reserved.