Search code examples
androidandroid-layoutandroid-volleyandroid-xmlsetcontentview

Activity consuming REST webservice using Volley library DOES NOT show layout loaded from XML (through setContentView())


I want to have an Activity which consumes REST API using the Volley library, meanwhile showing a custom layout (written in XML layout file) on the screen.

So I wrote an Activity which, in its onCreate() calls setContentView(R.layout.layout_file); like usual. The after that, it consumes the REST API through Volley library (i.e. builds the Volley's RequestQueue object and then calls requestQueueObject.add(requestObject) on it).

The (relevant parts of the) code are given as follows.

The problem is that while the data is being downloaded from the REST API, the layout loaded from the XML layout file using setContentView() (in onCreate() before consuming the REST web service) is NOT shown on the screen, and the screen remains blank. Then after that while, the layout defined in XML is shown momentarily, like for the blink of an eye, and then the next activity AnotherActivity is started.

From the next Activity, if I press the back button, then the layout set in the XML is shown in the first Activity.

How do I fix this problem?

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_first);

        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

        RequestQueue requestQueue = RequestQueueSingleton.getInstance(getApplicationContext()).getRequestQueue();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        ...
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ...
                    }
                });

        requestQueue.add(request);

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        startActivity(new Intent(this, AnotherActivity.class));
    } 

Solution

  • You should learn a bit more about Acitivty lifecycle and threads.

    First - you don't see the Activity till the onResume stage. So while you make the thread sleep within the onCreate stage, onResume can't be reached (that's why you see the blank screen).

    Second - you should not rely on timing to figure out when request is finished. Instead, start the desired activity within the callback methods (Response.Listener<JSONObject> and/or Response.ErrorListener())