Fetch data in background and display in UI

对着背影说爱祢 提交于 2020-01-30 11:46:05

问题


I'm using volley to fetch data using volley and display in User Interface, and it takes time to load the data. What i want to happen is, I want to fetch the data in background during the splash screen or loading screen and display it in User interface. I want the fetching part to be done in another activity and it should be a background service and this should be called in "main activity" to populate the fields.


回答1:


You can try using the AsyncTask. So the process goes like that:

  • In onPreExecute() you can show a ProgresDialog or a ProgresBar to visualize your loading process
  • in doInBackground(Params...) you start loading your data
  • and in onPostExecute(Result) you display your data in UI and hide your ProgresDialog/ProgresBar.

Example of AsyncTask usage.

Do it like this:

private class LoadDataBaseData extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        //Start loading your data 

        return "Data loaded";
    }

    @Override
    protected void onPostExecute(String result) {
       //Update your UI with data you loaded/start your activity with loaded data

    }

    @Override
    protected void onPreExecute(){     
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}



回答2:


use AsyncTask like that

 private class LongOperation extends AsyncTask<String, Void, String>
   {

    @Override
    protected String doInBackground(String... params)
    {
       //do your work here 


        return "Executed";
    }

    @Override
    protected void onPostExecute(String result)
    {
        progressBar.dismiss();

    }

    @Override
    protected void onPreExecute()
    {
        progressBar = ProgressDialog.show(getActivity(), null, "message...");
        progressBar.show();
    }

    @Override
    protected void onProgressUpdate(Void... values)
    {
    }
}


来源:https://stackoverflow.com/questions/51647605/fetch-data-in-background-and-display-in-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!