2

I'm having a problem with the findViewById. I'm trying to call this function but it always returns null.

I have only one activity in my app, MainActivity, in which I am passing params to POST request using Volley to a model that is hosted on Heroku. The model is working fine when I am passing the parameters on Postman Application.

Checking my Heroku logs, I noticed I am getting the error that the parameters that I am passing through the android application, they are NoneType.

Have tried String.Format and passing the url and params as a GET request using volley, but still I can see that only the parts of the url I specified as a string are being passed and the places where params were passed are empty.

Here is the code for my MainActivity:

public class MainActivity extends AppCompatActivity {
EditText a_ge,g_ender,h_eight,w_eight, a_p_hi,a_p_lo,c_holestrol,g_luc,s_moke,a_lco,a_ctive;
Button predict;
TextView result;
String url = "https://hridaya.herokuapp.com/predict";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    a_ge = findViewById(R.id.age);
    a_p_hi = findViewById(R.id.ap_hi);
    predict = findViewById(R.id.predict);
    result = findViewById(R.id.result);

And the method which I am using to pass the POST request:

predict.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // hit the API -> Volley
            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("Cardio");
                                if(data.equals("1")){
                                    result.setText("You are at Risk");
                                }else{
                                    result.setText("Not at Risk");
                                }
                            } 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",a_ge.getText().toString());
                    params.put("gender",g_ender.getText().toString());
                    params.put("height",h_eight.getText().toString());
                    params.put("weight",w_eight.getText().toString());
                    params.put("ap_hi",a_p_hi.getText().toString());
                    params.put("ap_lo",a_p_lo.getText().toString());
                    params.put("cholesterol",c_holestrol.getText().toString());
                    params.put("glucose",g_luc.getText().toString());
                    params.put("smoke",s_moke.getText().toString());
                    params.put("alcohol",a_lco.getText().toString());
                    params.put("active",a_ctive.getText().toString());
                    return params;
                }
            };
            RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
            queue.getCache().clear();
            queue.add(stringRequest);

The code in my activity_main.xml looks like the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="vertical">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="UselessParent">
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Heart Disease Predictor"
    android:textSize="30sp"
    android:textAlignment="center"
    android:layout_marginTop="30dp"/>

        <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Your Age"
        android:id="@+id/age"
        android:layout_marginTop="20dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Please Specify Your Gender"
        android:id="@+id/gender"
        android:layout_marginTop="20dp" />

</ScrollView>

I have tried several of the available solutions, but am still unable to rectify the error.

Please help in finding out the issues in my code, thanks!!

  • Dont post a hundred findViewById()s and so much EditText's. You should be able to tell us your problem with only one of each. – blackapps Jan 25 '22 at 20:18
  • @blackapps Have updated my question, please help with finding out where I am going wrong – Satvik Kaul Jan 25 '22 at 20:21
  • `predict = findViewById(R.id.predict); result = findViewById(R.id.result);` If really always null is returned then why do you yet post other code? – blackapps Jan 25 '22 at 20:51

1 Answers1

1

If the request reaches the server, either findViewById() returns an object or the getParams() method is not called. If findViewById() indeed returns a null value the app would throw a NullPointerException when calling getText() for the view. Have you tried logging the contents of the TextViews in getParams?

String v = a_ge.getText().toString();
Log.i("req param", "param age = " + v);

Also have a look at this: Volley not calling getParams() for standard POST request

I recommend avoiding volley for simple HTTP (at least if you haven't time to configure and troubleshoot its quirks) as it is likely to give you grief due to its erratic behavior (response caching, threading, request queuing and all that) and make you spend time checking out what its doing instead of testing your api.

Using a plain HttpUrlConnection or retrofit if you really want to get fancy might be quicker and more pleasant.

Crispert
  • 1,102
  • 7
  • 13