2016-08-02 42 views
2

我有MainActivity其中添加了兩個片段選項卡,即「tab1和」tab2.tab 1在此過程中發送一些請求到服務器我想顯示進度對話框,但是當我通過錯誤消息「android.view.WindowManager $ BadTokenException:無法添加窗口 - 令牌null不是一個應用程序」,也有在標籤1段廣播接收器的一些實施也通過錯誤‘無法註冊接收器’如何在andorid中的片段選項卡中創建進度對話框?

進度對話框代碼: -

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; 

} 

}

Mainactivity 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) { 

     } 
    }); 

和TAB1片段標籤的代碼: -

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<CDealAppDatastorage> 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<String, String> 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<>();// 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<JSONObject>() { 
      @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 < 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(); 
    } 

} 

回答

0

第一步:更改DialogUtils類:

public static ProgressDialog showProgressDialog(Activity activity, String message) { 
    ProgressDialog m_Dialog = new ProgressDialog(activity); 
    m_Dialog.setMessage(message); 
    m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
    m_Dialog.setCancelable(false); 
    m_Dialog.show(); 
    return m_Dialog; 

} 

第二步:改變postDealListingDatatoServer()方法。

m_Dialog = DialogUtils.showProgressDialog(getActivity(), "Loading..."); 

第3步:關於廣播接收器。請在onResume()方法中註冊,並在onPause()方法中取消註冊。

+0

這是我展示錯誤: - java.lang.IllegalArgumentException異常:查看= com.android.internal.policy.impl.PhoneWindow $ DecorView {41fdc330 VE .... [R ...... d 0 ,0-456,144}不附着於窗口管理器 – Raj

+0

在這一行: - – Raj

+0

jsonObjectRequest jsonObjectRequest =新jsonObjectRequest(Request.Method.POST,m_DealListingURL,的JSONObject,新Response.Listener (){ \t \t \t \t @Override \t \t \t \t public void onResponse(JSONObject response){ \t \t \t \t \t Log.i(TAG,「服務器響應: - 」+響應); \t \t \t \t \t如果(m_Dialog = NULL && m_Dialog.isShowing()!){ \t \t \t \t \t \t m_Dialog.dismiss(); \t \t \t \t \t} – Raj

0
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); 
    if (!((Activity) context).isFinishing()) { 
     m_Dialog.show(); 
    } 

    return m_Dialog; 
} 

要關閉對話框:

if ((m_Dialog!= null) && m_Dialog.isShowing()) 
    m_Dialog.dismiss(); 
0

檢查片段可見或不可見。

@Override 
    public void setUserVisibleHint(boolean isVisibleToUser) { 
     super.setUserVisibleHint(isVisibleToUser); 
     if (this.isVisible()) { 
      // If we are becoming invisible, then... 

      if (!isVisibleToUser) { 

       } 

      } else { 

      } 
     } 
    } 
相關問題