Search code examples
javaandroidandroid-fragmentsandroid-asynctask

How to stop the AsyncTask while switching Fragments?


I'm using Bottom Navigation Bar,Asynctask not working while switching fragments,Need to wait 8 to 10 minutes for getting response from asynctask. All pages are have no data to display due to Asynctask problem. Please help me to solve this issue.Thankyou Fragment switching code:

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected( MenuItem item) {
        Fragment fragment=null;
        switch (item.getItemId()) {
            case R.id.navigation_home:
                fragment = new HomeFragment();
                break;
            case R.id.navigation_market:
                fragment=new MarketFragment();
                break;
            case R.id.navigation_agent:
                fragment=new AgentFragment();
                break;
            case R.id.navigation_finance:
                fragment=new FinanceFragment();
                break;
           /* case R.id.navigation_more:
                MoreFragment moreFragment=new MoreFragment();
                moreFragment.show(getSupportFragmentManager(),moreFragment.getTag());*/
        }
        closeContextMenu();
        return loadFragment(fragment);
    }
};
private boolean loadFragment(Fragment fragment) {
    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .commit();
        return true;
    }
    return false;
}```

Asynctask Code: I have implement asynctask like this in all fragments.

        JSONObject jsonObject, jsonObject2;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            SignupActivity.this.layoutProgress.setVisibility(View.VISIBLE);
        }
        @Override
        protected String doInBackground(Void... voids) {
            HashMap<String, String> map = new HashMap<>();
            map.put("countrycode",code);
            map.put("phonenumber",phone);
            map.put("emailid",email);
            map.put("agentname",fullname);
            map.put("username",username);
            map.put("password",lpassword);
            map.put("confirmpassword",conlpassword);
            map.put("transactionpassword",spassword);
            map.put("transactionconfirmpassword",conspassword);
            return new HttpHandler().sendPostRequest(Config.url + "JoinNowRegister",map);
        }
        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);
            Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();
            try {
                jsonObject = new JSONObject(response);
                if(jsonObject.getString("statuscode").equals("1")){
                    message = jsonObject.getString("status");
                    jsonObject2 = jsonObject.getJSONObject("data");
                    id = jsonObject2.getString("agentid");
                    int code=Integer.parseInt(jsonObject2.getString("countrycode"));
                    String phonenumber= jsonObject2.getString("phone");
                    storeCode(code);
                    storePhone(phonenumber);
                    Intent intent;
                    intent = new Intent(SignupActivity.this, OtpActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("agentid",id);
                    intent.putExtras(bundle);
                    startActivity ( intent );
                    finish();
                }
                else{
                    msg=jsonObject.getString("data");
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            SignupActivity.this.layoutProgress.setVisibility(View.GONE);
        }
    }   

Solution

  • Use parallel execution.

     task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);