问题
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