Issue
I have to make an expensive call to a remote server when a Fragment is loaded. I am using the default Dashboard activity with NavigationView to change the fragments. However whenever a fragment is loaded, it freezes the UI for a few seconds while executing the AsyncTask containing the SOAP Request code.
I have already tried to execute the AsyncTask from onAttach()
and onStart()
but it still freezes the UI.
How can I fix the UI freezing?
Edit :- The async task code:-
private class BindTreasuryTask extends AsyncTask<Void,Void,ArrayList<TreasuryData>> {
private boolean NO_INTERNET;
@Override
protected ArrayList<TreasuryData> doInBackground(Void... voids) {
try {
// SOAP Call returns a JSONArray
JSONArray jsonArray = apiHandler.performBindTreasury(payeeid);
ArrayList<TreasuryData> td = new ArrayList<>();
td.add(new TreasuryData("Select a treasury","none","none"));
for(int i =0; i<jsonArray.size(); i++){
JSONObject j = (JSONObject) jsonArray.get(i);
td.add(new TreasuryData(j.get("TREASURY_NAME"),j.get("TREAS_CODE"),j.get("SCHEMA_NM")));
}
return td;
} catch (IOException e) {
NO_INTERNET = true;
e.printStackTrace();
} catch (XmlPullParserException | ParseException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(ArrayList<TreasuryData> treasuryData ) {
if (treasuryData == null){
if (NO_INTERNET){
Toast.makeText(getActivity(),"No Internet Connection",Toast.LENGTH_LONG).show();
}
} else {
ArrayList<String> treasury = new ArrayList<>();
for(int i=0;i<treasuryData.size();i++){
treasury.add(treasuryData.get(i).getTreasuryName());
}
setUpView();
}
}
}
Solution
As Ashok answered you can call AsyncTask in onActivityCreated() method. You may use thread or handler to start the SOAP request with 1-2 secs delay that may avoid freezing of fragment upon calling Api. Or if UI is freezing whenever you're switching fragments from navigation drawer then you may have to manage your own fragment queue.
Answered By - Sanket Patel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.