The app is crashing as soon as I open it. It says its a null pointer exception.
This is what the logcat shows:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'voidandroid.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.titanic_survival_prediction.MainActivity.onCreate(MainActivity.java:48)
Here is the full code:
public class MainActivity extends AppCompatActivity {
EditText age, sex, pclass, embarked, fare, sibsp, parch;
Button predict;
TextView result;
String url = "https://titanic-android-app.herokuapp.com/predict";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
age = findViewById(R.id.age);
sex = findViewById(R.id.sex);
pclass = findViewById(R.id.pclass);
embarked = findViewById(R.id.embarked);
fare = findViewById(R.id.fare);
sibsp = findViewById(R.id.sibsp);
parch = findViewById(R.id.parch);
result = findViewById(R.id.result);
predict.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Hit the API
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String data = jsonObject.getString("Survived");
if (data.equals("1")){
result.setText("You Survived");
}
else{
result.setText("You Died");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("Age_band", age.getText().toString());
params.put("Sex", sex.getText().toString());
params.put("Pclass", pclass.getText().toString());
params.put("Embarked", embarked.getText().toString());
params.put("Fare_cat", fare.getText().toString());
params.put("Sibsp", sibsp.getText().toString());
params.put("Parch", parch.getText().toString());
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(stringRequest);
}
});
}
}
This is the part where its logcat shows null pointer exception:
predict.setOnClickListener(new View.OnClickListener() {
There is no problem with the xml file. This app uses an ML model which I made and deployed on heroku.