TensorFlow Lite Android App crashes with NullPointerException 'void android.widget.TextView.setText(java.lang.CharSequence)' on null object reference

rishijoshi :

I'm working on an Android app that takes input from the user and passes it to a TensorFlow machine learning model which has been converted to tflite for prediction. However my app crashes after taking the input. After the app I wrote did not work, I used the code from the YouTube tutorial which I'm following to get some insight. But I get the same error in both cases. Here is the code.

import androidx.appcompat.app.AppCompatActivity;

import android.content.*;
import android.content.res.*;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import org.tensorflow.lite.Interpreter;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;

import android.os.Bundle;

public class Input_Activity_2 extends AppCompatActivity{

    EditText inputNumber;
    Button inferButton;
    TextView outputNumber;
    Interpreter tflite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input__2);
        inputNumber=(EditText)findViewById(R.id.inputNumber);
        outputNumber=(TextView)findViewById(R.id.outputNumber);
        inferButton=(Button)findViewById(R.id.inferButton);

        //final int getText1=Integer.parseInt(inputNumber.getText().toString());

        try{
            tflite=new Interpreter(loadModelFile());
        }catch(Exception ex){
            ex.printStackTrace();
        }
        //When we click the infer button, we should do the inference
        inferButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                float prediction=doInference(inputNumber.getText().toString());
                outputNumber.setText(Float.toString(prediction));
            }
        });
    }
    public float doInference(String inputString){
        //Input shape is [1]. Single valued input
        float[] inputVal=new float[1];
        inputVal[0]=Float.valueOf(inputString);

        //Output shape is [1][1]
        float[][] outputval=new float[1][1];

        //Run inference passing the input shape and getting the output shape
        tflite.run(inputVal, outputval);

        //Inferred value is at [0][0]
        float inferredValue=outputval[0][0];

        return inferredValue;
    }
    private MappedByteBuffer loadModelFile() throws IOException {
        AssetFileDescriptor fileDescriptor=this.getAssets().openFd("test_linear.tflite");
        FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
        FileChannel fileChannel = inputStream.getChannel();
        long startOffset = fileDescriptor.getStartOffset();
        long declaredLength = fileDescriptor.getDeclaredLength();
        return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
    }
}

And here is the python code

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow import lite

model=keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs=np.array([-1.0,0.0,1.0,2.0,3.0,4.0],dtype=float)
ys=np.array([-3.0,-1.0,0.0,3.0,5.0,7.0],dtype=float)

model.fit(xs,ys,epochs=500)
print(model.predict([10.0]))

keras_file="test_linear.h5"
keras.models.save_model(model,keras_file)
converter=lite.TocoConverter.from_keras_model_file(keras_file)
tflite_model=converter.convert()
open("test_linear.tflite","wb").write(tflite_model)

I get the following error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.androidfirebaseauth2019, PID: 10695
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.androidfirebaseauth2019.Input_Activity_2$1.onClick(Input_Activity_2.java:48)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Any help is appreciated. Thanks.

Edit:-

Here is my activity_input_2

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:exported="true"
    tools:context=".Input_Activity_2">


    <EditText
        android:id="@+id/inputNumber"
        android:layout_width="221dp"
        android:layout_height="0dp"
        android:layout_marginTop="150dp"
        android:layout_marginBottom="34dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/inferButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/inferButton"
        android:layout_width="218dp"
        android:layout_height="0dp"
        android:layout_marginBottom="55dp"
        android:text="Find my Organ!"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputNumber" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="22dp"
        android:layout_marginEnd="22dp"
        android:layout_marginBottom="97dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inferButton" />

</androidx.constraintlayout.widget.ConstraintLayout>
Ryan Mentley :

You are trying to find a TextView that does not exist in your activity_input__2.xml. You have an inputNumber, but no outputNumber, so this call returns null:

outputNumber=(TextView)findViewById(R.id.outputNumber);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=24895&siteId=1