title: How to make progress dialog in fragment tab in Android?
body: <p>I have MainActivity which added two fragment tab namely "tab1 and "tab2.tab 1 sends some request to server during this process I Want to show a progress dialog but when I do this through a error message "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application" and also have some implementation of Broadcast receiver in tab 1 fragment which also through error "unable to register receiver"</p>
  
  <p>Progress dialog code:</p>
  
  <pre><code>public class DialogUtils {
  
      public static ProgressDialog showProgressDialog(Context context, String message) {
          ProgressDialog m_Dialog = new ProgressDialog(context);
          m_Dialog.setMessage(message);
          m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
          m_Dialog.setCancelable(false);
          m_Dialog.show();
          return m_Dialog;
  
      }
  
  }
  </code></pre>
  
  <p>Mainactivity code:</p>
  
  <pre><code>m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
      m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
      m_TabLayout.addTab(m_TabLayout.newTab().setText("Deals"));// add deal listin tab
      m_TabLayout.addTab(m_TabLayout.newTab().setText("Stories"));
      m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
  
  
      CDealMainListingPager m_oDealMainScreenPager = new CDealMainListingPager(getSupportFragmentManager(), m_TabLayout.getTabCount());
      m_ViewPager.setAdapter(m_oDealMainScreenPager);// adiing adapter to ViewPager
      m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
      m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
          @Override
          public void onTabSelected(TabLayout.Tab tab) {
              m_ViewPager.setCurrentItem(tab.getPosition());
          }
  
          @Override
          public void onTabUnselected(TabLayout.Tab tab) {
  
          }
  
          @Override
          public void onTabReselected(TabLayout.Tab tab) {
  
          }
      });
  </code></pre>
  
  <p>and tab1 fragment tab code:</p>
  
  <pre><code>public static final String TAG = CDealAppListing.class.getSimpleName();
  public static final int m_TRANSACTION_SUCCESSFUL = 0;
  public static String m_szMobileNumber;//declaring String mobile number variable
  public static String m_szEncryptedPassword;//declaring string password  variable
  public static String sz_RecordCount;// //declaring String record count variable variable
  public static String sz_LastCount;//declaring String lastcount  variable
  private static ListView m_ListView;// declaring Listview variable..
  private static CDealAppListingAdapter m_oAdapter;// declaring DealListingAdapter..
  public CDealAppDatastorage item;// declaring DealAppdataStorage
  public View mFooter;
  public AppCompatButton m_BtnRetry;
  /*This Broadcast receiver will listen network state accordingly
  which enable or disable create an account button*/
  private final BroadcastReceiver m_oInternetChecker = new BroadcastReceiver() {// creating broadcast to receive otp sent by server from Inbox...
      @Override
      public void onReceive(Context context, Intent intent) {// on receive method to read OTP sent by server
          changeButtonState();// check whether edit text is empty or not
  
      }
  };
  RequestQueue requestQueue;
  JsonObjectRequest jsonObjectRequest;
  private ArrayList&lt;CDealAppDatastorage&gt; s_oDataset;// declaring Arraylist variable
  private int[] m_n_FormImage;//declaring integer array varaible
  private View m_Main;//declaring View variable
  private int m_n_DefaultRecordCount = 5;// intiallly record count is 5.
  private int m_n_DeafalutLastCount = 0;//initally lastcount is 0.
  private SwipeRefreshLayout mSwipeRefresh;
  private ProgressDialog m_Dialog;
  private boolean bBottomOfView;
  private LinearLayout m_NoInternetWarning;
  
  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      m_Main = inflater.inflate(R.layout.deal_listing, container, false);//intialize mainLayout
      Log.i(TAG, "OnCreateView.........");
      init();
      return m_Main;
  }
  
  @Override
  public void onResume() {
      super.onResume();
      Log.i(TAG, "onResume.........");
      /*Registered Broadcast receiver*/
      IntentFilter m_intentFilter = new IntentFilter();// creating object of Intentfilter class user for defining permission
      m_intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");// action to check Internet connection
      getActivity().registerReceiver(m_oInternetChecker, m_intentFilter);// register receiver....
  
      getDetails();
  
  }
  
  
  public void changeButtonState() {
      if (NetworkUtil.isConnected(getActivity())) {
          m_BtnRetry.setEnabled(true);
          m_BtnRetry.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
      } else {
          m_BtnRetry.setEnabled(false);
          m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
      }
  }
  
  private void getDetails() {// get details of user from shared preference...
      CLoginSessionManagement m_oSessionManagement = new CLoginSessionManagement(getActivity());// crating object of Login Session
      HashMap&lt;String, String&gt; user = m_oSessionManagement.getLoginDetails();// get String from Login Session
      m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();// getting password from saved preferences..........
      m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();// getting mobile num from shared preferences...
  
      sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
      m_n_DeafalutLastCount = 0;
      sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
  
      s_oDataset = new ArrayList&lt;&gt;();// making object of Arraylist
  
  
      if (NetworkUtil.isConnected(getActivity())) {
          m_NoInternetWarning.setVisibility(View.GONE);
          postDealListingDatatoServer();// here sending request in onCreate
      } else {
          mSwipeRefresh.setVisibility(View.GONE);
          m_NoInternetWarning.setVisibility(View.VISIBLE);
          m_BtnRetry.setEnabled(false);
          m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
  
      }
  }
  
  
  @Override
  public void onDestroy() {
      super.onDestroy();
      Log.i(TAG, "onDestroy...............");
      getActivity().unregisterReceiver(m_oInternetChecker);// unregistaer broadcast receiver.
  }
  
  private void init() {// initialize controls
  
      m_NoInternetWarning = (LinearLayout) m_Main.findViewById(R.id.no_internet_warning);
      m_BtnRetry = (AppCompatButton) m_Main.findViewById(R.id.btn_retry);
      m_BtnRetry.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              retryRequest(v);
          }
      });
      m_ListView = (ListView) m_Main.findViewById(R.id.dealList);// findind Id of Listview
      m_ListView.setFadingEdgeLength(0);
      m_ListView.setOnScrollListener(this);
      /*Swipe to refresh code*/
      mSwipeRefresh = (SwipeRefreshLayout) m_Main.findViewById(R.id.swipe);
      mSwipeRefresh.setColorSchemeResources(R.color.refresh_progress_1);
  
      mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
          @Override
          public void onRefresh() {
              /*Here check net connection avialable or not */
              if (NetworkUtil.isConnected(getActivity())) {
                  new Handler().postDelayed(new Runnable() {
                      @Override
                      public void run() {
                          sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
                          m_n_DeafalutLastCount = 0;
                          sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
                          swipeData();
                      }
                  }, 3500);
  
              } else {
                  m_NoInternetWarning.setVisibility(View.VISIBLE);
                  mSwipeRefresh.setVisibility(View.GONE);
                  if (mSwipeRefresh.isRefreshing()) {
  
                      mSwipeRefresh.setRefreshing(false);
                  }
              }
          }
      });
      m_n_FormImage = new int[]{// defining Images in Integer array
              R.drawable.amazon,
              R.drawable.whatsapp,
              R.drawable.zorpia,
              R.drawable.path,
              R.drawable.app_me,
              R.drawable.evernote,
              R.drawable.app_me};
  }
  
  public void retryRequest(View v) {
      if (NetworkUtil.isConnected(getActivity())) {
          m_BtnRetry.setEnabled(true);
          m_BtnRetry.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
          sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
          m_n_DeafalutLastCount = 0;
          sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
  
          postDealListingDatatoServer();
      } else {
          m_BtnRetry.setEnabled(false);
          m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
      }
  
  }
      /*This is new changes in code ....using Volley instead of AsynkTask*/
  
  /*This method send request to server for deallisting*/
  // this method send request to server for deal list....
  public void postDealListingDatatoServer() {
      try {
          String json;
          // 3. build jsonObject
          final JSONObject jsonObject = new JSONObject();// making object of Jsons.
          jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
          jsonObject.put("pin", m_szEncryptedPassword);// put password
          jsonObject.put("recordcount", sz_RecordCount);// put record count
          jsonObject.put("lastcountvalue", sz_LastCount);// put last count
          System.out.println("Record Count:-" + sz_RecordCount);
          System.out.println("LastCount:-" + sz_LastCount);
          // 4. convert JSONObject to JSON to String
          json = jsonObject.toString();// convert Json object to string
  
          Log.i(TAG, "Server Request:-" + json);
          m_Dialog = DialogUtils.showProgressDialog(getActivity().getApplicationContext(), "Loading...");
          final String m_DealListingURL = "http://202.131.144.132:8080/json/metallica/getDealListInJSON";
          JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener&lt;JSONObject&gt;() {
              @Override
              public void onResponse(JSONObject response) {
                  Log.i(TAG, "Server Response:-" + response);
                  m_Dialog.dismiss();
                  try {
                      int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
                      if (nResultCodeFromServer == m_TRANSACTION_SUCCESSFUL) {
                          JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
                          s_oDataset.clear();
                          for (int i = 0; i &lt; posts.length(); i++) {// loop for counting deals from server
                              JSONObject post = posts.getJSONObject(i);// counting deal based on index
                              item = new CDealAppDatastorage();// creating object of DealAppdata storage
                              item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
                              item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
                              item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
                              item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
                              s_oDataset.add(item);// add all items in ArrayList
  
                          }
  
  
                          if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
                              m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
                              m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
                              m_NoInternetWarning.setVisibility(View.GONE);
                              mSwipeRefresh.setVisibility(View.VISIBLE);
  
                          } else {
                              m_ListView.removeFooterView(mFooter);// else Load buttonvisibility set to Gone
                          }
                      }
                      if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
                          CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
                      } else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
                          CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
                      } else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
                          CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
                      }
  
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              }
          }, new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                  Log.e(TAG, "Server error:-" + error);
                  m_Dialog.dismiss();
                  if (error instanceof TimeoutError) {
                      CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection lost ! Please try again", getActivity());
                  } else if (error instanceof NetworkError) {
                      CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No internet connection", getActivity());
                      mSwipeRefresh.setVisibility(View.GONE);
                      m_NoInternetWarning.setVisibility(View.VISIBLE);
                  }
  
              }
          });
          RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
          requestQueue.add(jsonObjectRequest);
      } catch (JSONException e) {
          e.printStackTrace();
      }
  }
  </code></pre>