Empty response from server in the Volley onResponse() method


#1

Hey guys.
I’m a having trouble implementing a certain functionality.
Here is my problem:
When an activity is launched i would like to display the name and picture/photo of a specific person.
The name and a url of the photo’s location are stored in a remote database (in my case i’m using wamp server i.e, localhost<phpMyAdmin,MySQL blah blah blah you know the rest>).
I’m using the volley library to make those network calls.
Firstly there is a method that fetches the person’s name and displays it in the activity then immediately after that there is a method that uses the person’s name to fetch the url of the person’s photo.
Then another method uses the url to fetch the actual image and set it on the ImageView in my activity.
Trouble is when i try to fetch the url i get an empty json string (i.e. response) from the server.
See my code snippet below.
I’ll also include the php script (API) which is relevent after the java code.
I have searched stackoverflow but to no avail.
Any help is appreciated thank you.
P.S. I’ve tested the php scripts using postman rest api client and they work fine A-Ok!!!

Code snippets:-

public class VoteForTheDeputyChairpersonActivity extends SessionTimeoutActivity implements View.OnClickListener {

private ImageView mProfilePicture;
private TextView mCandidateName;
private Button mViewManifestoButton, mVoteButton, mNextCandidateButton;
private String mUserName, mUserId, mCandidatesImageUrl, mCandidatesNameToBeReturned, mGetCandidatesNameThatWasReturned;
private int getJsonObject = 0;

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

    mHandler = new Handler();
    mRunnable = new Runnable() {
        @Override
        public void run() {
            Toast.makeText(VoteForTheDeputyChairpersonActivity.this, "You have been inactive for the last minute.", Toast.LENGTH_LONG).show();
            SharedPrefManager.getInstance(getApplicationContext()).logout(mUserId, mUserName);
            finish();
            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        }
    };
    startHandler();

    mProfilePicture = (ImageView) findViewById(R.id.profile_picture);
    mCandidateName = (TextView) findViewById(R.id.candidate_name);
    mViewManifestoButton = (Button) findViewById(R.id.manifesto);
    mVoteButton = (Button) findViewById(R.id.vote);
    mNextCandidateButton = (Button) findViewById(R.id.next_candidate);

    mNextCandidateButton.setOnClickListener(this);
    mVoteButton.setOnClickListener(this);
    mViewManifestoButton.setOnClickListener(this);

    getCandidateInfo();

    mGetCandidatesNameThatWasReturned = getCandidateInfo();

    passCandidatesFullNameToTheServer(mGetCandidatesNameThatWasReturned);

    getCandidatesImageUrl();

    getCandidateImage();
}

private void passCandidatesFullNameToTheServer(String fullName) {
    final String full_name = fullName;

    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            Constants.URL_PASS_CANDIDATES_FULL_NAME,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("full_name", full_name);
            return params;
        }
    };

    RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}

private void getCandidatesImageUrl() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                Constants.URL_GET_CANDIDATES_IMAGES,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("the response contains: ", "" + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray result = jsonObject.getJSONArray(Constants.JSON_ARRAY);
                            JSONObject candidateImageUrl = result.getJSONObject(getJsonObject);
                            mCandidatesImageUrl = candidateImageUrl.getString(Constants.KEY_URL);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

        RequestHandler.getInstance(this).addToRequestQueue(stringRequest);

    }

private void getCandidateImage() {
    final ImageRequest imageRequest = new ImageRequest(mCandidatesImageUrl,
            new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap response) {
                    mProfilePicture.setImageBitmap(response);
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, null,
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(VoteForTheDeputyChairpersonActivity.this, "Something went wrong.", Toast.LENGTH_LONG).show();
                    error.printStackTrace();
                }
            });

    // Create a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    // Add the request queue to the queue
    requestQueue.add(imageRequest);

}

private String getCandidateInfo() {

    String url = Constants.URL_SEE_CANDIDATE_INFO_DEPUTY_CHAIRPERSON;

    StringRequest stringRequest = new StringRequest(url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray result = jsonObject.getJSONArray(Constants.JSON_ARRAY);
                        JSONObject candidateDetails = result.getJSONObject(getJsonObject);
                        mCandidateName.setText(candidateDetails.getString(Constants.KEY_NAME));
                        mCandidatesNameToBeReturned = candidateDetails.getString(Constants.KEY_NAME);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    // Create a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    // Add the request queue to the queue
    requestQueue.add(stringRequest);

    return mCandidatesNameToBeReturned;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.next_candidate:
            getJsonObject++;
            getCandidateInfo();
            getCandidateImage();
            break;
        case R.id.vote:
            break;
        case R.id.manifesto:
            startActivity(new Intent(this, ReadCandidatesManifestoActivity.class));
            break;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    KuraMenuOptions kuraMenuOptions = new KuraMenuOptions();

    switch (item.getItemId()) {
        case R.id.menuLogout:
            SharedPrefManager.getInstance(this).logout(mUserId, mUserName);
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            break;
        case R.id.menuAbout:
            kuraMenuOptions.kuraAbout();
            break;
        case R.id.menuHelp:
            kuraMenuOptions.kuraSupport();
            break;
    }
    return true;
}

}

PHP Scripts a.k.a APIs:-

[passCandidatesFullNameToTheServer.php]

<?php $name = $_POST['full_name']; [getCandidatesImages.php] <?php header('Content-type=application/json; charset=utf-8'); include 'passCandidatesFullNameToTheServer.php'; define('DB_NAME', 'kura'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); $response = array(); $con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die('Unable to Connect'); $sql = "SELECT url FROM candidates_images WHERE name = '$name'"; $r = mysqli_query($con, $sql); while ($row = mysqli_fetch_array($r)) { array_push($response, array( 'url'=>$row['url'] )); } header('Content-Type: application/json'); echo json_encode(array('result'=>$response));

#2

I think the problem here is that you are using String Request in Volley, but the server is sending you a Json object back. So the string is null. So the String Response field is null.