tsil
tsil

Reputation: 2069

Android call to webservice returns no result although the URL works fine

This the most bizarre problem I have ever seen. I get "No product available" although there are products in my database.

Here my service:

public class AllProductsService {

private String URL = "xxxx";

Gson gson;

public AllProductsService(int page) {
    gson = new Gson();
    URL = URL + "?page=" + Integer.toString(page);
}

private InputStream sendRequest(URL url) throws Exception {

    try {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.connect();

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return urlConnection.getInputStream();
        }
    } catch (Exception e) {
        throw new Exception("");
    }

    return null;
}

public List<Product> getProducts() {

    try {

        InputStream inputStream = sendRequest(new URL(URL));


        if(inputStream != null) {

            InputStreamReader reader = new InputStreamReader(inputStream);

            return gson.fromJson(reader, new TypeToken<List<Product>>(){}.getType());
        }

    } 
    catch (Exception e) {

    }
    return null;
}
}

And my AsyncTask class:

private class AllProductsTask extends AsyncTask<Void, Void, List<Product>> {

    @Override
    protected void onPreExecute() {
        setSupportProgressBarIndeterminateVisibility(true);
    }

    @Override
    protected List<Product> doInBackground(Void... params) {

        AllProductsService allProductsService = new AllProductsService(current_page);
        List<Product> liste = allProductsService.getProducts();

        if (liste != null && liste.size() >= 1)
            return liste;

        return new ArrayList<Product>();
    }

    protected void onPostExecute(java.util.List<Product> result) {

        setSupportProgressBarIndeterminateVisibility(false);

        if (result.isEmpty() && isInternetPresent && current_page < 2) {
            Crouton.makeText(MainActivity.this, "No product available!", Style.ALERT).show();
        }

        //populate adapter
    }   
}

When I call the URL from the browser, results are displayed correctly. I also try with a different URL with the same code and it works fine. I don't know why.

Upvotes: 1

Views: 111

Answers (2)

tsil
tsil

Reputation: 2069

I found the solution: just have to remove the slash at the end of the URL. Thank you @trevor-e. Knowing the HTTP code status help me.

Upvotes: 0

Husnain Iqbal
Husnain Iqbal

Reputation: 466

I think problem is; you are returning the

new ArrayList<Product>();

in doInBackground() of Asynctask which is null. You should return the liste here. or place the return new ArrayList<Product>(); in else condition

Upvotes: 1

Related Questions