【问题标题】:ProgressDialog Before AlertDialog in AndroidAndroid中AlertDialog之前的ProgressDialog
【发布时间】:2018-02-24 03:15:36
【问题描述】:

在屏幕上有Button. 一旦使用点击Button 和AsyncTask 将执行并从数据库中获取数据并显示在AlertDialog. ButtonClick 和AlertDialog 之间的时间需要显示CircularProgressBar.

我的代码写在下面,但没有显示进度条。

该要求的任何其他解决方法。

 public void Select_PaymentMonths(String selectFlatNumber)
   {

    /*
    progressBarLoadData = new ProgressDialog(get ApplicationContext());
    progressBarLoadData.setMessage("Please Wait....");
    progressBarLoadData.show();
    */
  //  ProgressDialog progressDialog = new ProgressDialog(this);
  //  progressDialog.setMessage("Please Wait......");
 //   progressDialog.show();
    //monthProgress.setVisibility(View.VISIBLE);

   //ProgressDialog progressDialog = new ProgressDialog(this);
    //  progressDialog.setMessage("Please Wait......");
    ProgressDialog progressDialog =   ProgressDialog.show(this,"Please Wait","Wait for loading Payment Month data");

    residentsPaymentInfo = new ArrayList<UserPaymentInfo>();
    ResidentsPaymentInfoHttpResponse getResidentsPaymentMonthDetails = new 
     ResidentsPaymentInfoHttpResponse();
    try {
    residentsPaymentInfo = 
            getResidentsPaymentMonthDetails.execute(selectFlatNumber).get();
        //monthProgress.setVisibility(View.GONE);
        progressDialog.dismiss();
        int notPaidMonthsCount = residentsPaymentInfo.size();
        List<String> listItems = new ArrayList<String>();


        for(int i=0; i<notPaidMonthsCount; i++ )
        {
            UserPaymentInfo userNotPaidMonthInfo = new UserPaymentInfo();
            userNotPaidMonthInfo = residentsPaymentInfo.get(i);

            //listItems.add(userNotPaidMonthInfo.getPaymentMonth() +","+ 
           userNotPaidMonthInfo.getPaymentoYear() +" - ₹" + 
            userNotPaidMonthInfo.getactualAmount() + "/-");
            listItems.add(userNotPaidMonthInfo.getPaymentMonth() +" "+ 
          userNotPaidMonthInfo.getPaymentoYear() +" ₹" + 
            userNotPaidMonthInfo.getactualAmount() + "/-");
        }

     final CharSequence[] items = listItems.toArray(new 
         CharSequence[listItems.size()]);
       // arraylist to keep the selected items
        final ArrayList seletedItems=new ArrayList();
        //progressBarLoadData.dismiss();
        //progressDialog.dismiss();
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("Select Payment Month Year Amount")
                .setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int 
               indexSelected, boolean isChecked) {
                        if (isChecked) {
                            // If the user checked the item, add it to the 
               selected items
                            //seletedItems.add(indexSelected);
                            seletedItems.add(indexSelected);
                        } else if (seletedItems.contains(indexSelected)) {
                            // Else, if the item is already in the array, 
       remove it

    seletedItems.remove(Integer.valueOf(indexSelected));
                        }
                    }
                }).setPositiveButton("OK", new 
      DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        Collections.sort(seletedItems);

                        String selectedMonths = "";
                        float totalAmount=0;
                        for(int i = 0 ; i < seletedItems.size(); i++) {
                            //selectedMonths = selectedMonths + items[(int)
          (seletedItems.get(i))];
                            selectedMonths = selectedMonths +             
  residentsPaymentInfo.get((int)seletedItems.get(i)).getPaymentMonth() +"-
 "+residentsPaymentInfo.get((int)seletedItems.get(i)).getPaymentoYear()+",";
                            totalAmount = totalAmount + 
residentsPaymentInfo.get((int)seletedItems.get(i)).getactualAmount();
                        }

                        paymentMonth.setText(selectedMonths);
                        amountPaid.setText(String.valueOf(totalAmount));
                //selectedMonths.split(",");
                //  Your code when user clicked on OK
                //  You can write the code  to save the selected item here

             }
       }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                  {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        //  Your code when user clicked on Cancel
                    }
                }).create();
        //return 50;
        dialog.show();

    }
    catch (Exception e)
    {
     //   e.printStackTrace();
    }

}

我已将代码 ProgressDialog 代码更新为如下所示的异步任务,但进度对话框仍未出现。

      public class ResidentsPaymentInfoHttpResponse extends 
     AsyncTask<String, Void, List<UserPaymentInfo>> {
     ProgressDialog pDialog;
      private Context MSAContext;
      public ResidentsPaymentInfoHttpResponse(Context context)
        {
           MSAContext = context;
         }

   @Override
       protected void onPreExecute(){
       pDialog = new ProgressDialog(MSAContext);
       pDialog.setMessage("Loading...");
        pDialog.show();
    }
   @Override
    protected List<UserPaymentInfo> doInBackground(String... params){
  String flatNo = params[0];
 String urls = "https://script.google.com/macros/s/";
 List<UserPaymentInfo> residentsMonthlyPayments = new ArrayList<>();

try {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(urls)
            .build();

    Response responses = null;

    try
    {
        responses = client.newCall(request).execute();
        String jsonData = responses.body().string();
        JSONObject jobject = new JSONObject(jsonData);
        JSONArray jarray = jobject.getJSONArray("ResidentsInfo");

        int limit = jarray.length();

        for(int i=0;i<limit; i++)
        {
            JSONObject object = jarray.getJSONObject(i);
            if(object.getString("FlatNo").equals(flatNo) && object.getString("PaymentStatus").equals("notpaid")) {
                UserPaymentInfo residentMaintePayment = new UserPaymentInfo();
                UserInfo residentInfo = new UserInfo();
                residentInfo.setUserFlatNo(object.getString("FlatNo"));
                residentInfo.setUserName(object.getString("Name"));
                residentInfo.setUserEamil(object.getString("OwnerEmail"));
                residentMaintePayment.setResidentData(residentInfo);
                residentMaintePayment.setactualAmount(object.getLong("Actualamountneedtopay"));
                residentMaintePayment.setPaymentYear(object.getInt("Year"));
                residentMaintePayment.setPaymentMonth(object.getString("Month"));
                residentsMonthlyPayments.add(residentMaintePayment);
            }
        }

    }

    catch (IOException e)
    {
      //  e.printStackTrace();
    }

}
catch (Exception ex)
{
   // ex.printStackTrace();
}
return residentsMonthlyPayments;
}

protected void onPostExecute(List<UserPaymentInfo> rusult){
super.onPostExecute(rusult);
    pDialog.dismiss();


}

}

在 Maintask 中调用异步任务,如下所示

ResidentsPaymentInfoHttpResponse getResidentsPaymentMonthDetails = new 
   ResidentsPaymentInfoHttpResponse(this);
     try {
        residentsPaymentInfo = 
     getResidentsPaymentMonthDetails.execute(selectFlatNumber).get();
        //monthProgress.setVisibility(View.GONE);
       // progressDialog.dismiss();
         int notPaidMonthsCount = residentsPaymentInfo.size();
         List<String> listItems = new ArrayList<String>();

进度条屏幕没有出现。

【问题讨论】:

    标签: android


    【解决方案1】:

    这不是直接改变你的代码,而是给你一个例子。 把你的逻辑放在 Thread.runnable 中,然后在完成你的工作后,关闭 ProgressDialog 。

    http://indyvision.net/2015/08/android-tutorials-show-a-progress-dialog-while-loading-data/

    //inside the runnable will be the logic that you want to run
        void showProgressDialog(final Context context, final Runnable runnable) {
            final ProgressDialog ringProgressDialog = ProgressDialog.show(context, "Title ...", "Info ...", true);
            //you usually don't want the user to stop the current process, and this will make sure of that
            ringProgressDialog.setCancelable(false);
            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {
    
                    runnable.run();
                    //after he logic is done, close the progress dialog
                    ringProgressDialog.dismiss();
                }
            });
            th.start();
        }
    

    【讨论】:

      【解决方案2】:

      AsyncTask 永远不会阻塞你的 UI 线程,它在后台运行。

      residentsPaymentInfo =getResidentsPaymentMonthDetails.execute(selectFlatNumber).get();
       progressDialog.dismiss();
      

      这里你已经直接调用了dismiss()方法,它不会等待getResidentsPaymentMonthDetails完成它直接关闭对话框也residentsPaymentInfo也是null或空白。

      你可以在ResidentsPaymentInfoHttpResponse中显示对话框

       private class ResidentsPaymentInfoHttpResponse extends AsyncTask<String,Void,String>{
                  ProgressDialog pDialog;
                  @Override
                   protected void onPreExecute(){
                      pDialog = new ProgressDialog(LoginActivity.this);
                      pDialog.setMessage("Loading...");
                      pDialog.show();
                   }
                  @Override
                  protected String doInBackground(String... params) {
                     //your logic
                      return null;
                  }
                  protected void onPostExecute(String params){
                      super.onPostExecute(params);
                      pDialog.dismiss();
      
                  }
      
               }
      

      【讨论】:

      • 我已更改代码以从异步任务调用 ProgressDialog。但是没有显示进度对话框。
      【解决方案3】:

      ProgressDialogsuppose 如何可见。您在同一块内初始化并dismiss() 它。它会在初始化后立即关闭。

      请参阅下面的代码。

       residentsPaymentInfo = 
              getResidentsPaymentMonthDetails.execute(selectFlatNumber).get();
      

      这里 residentsPaymentInfo 似乎是 AsyncTask 或 Executor 最终是后台线程。所以这将在其他线程上运行,并且您的代码“progressDialog.dismiss()”在初始化后立即执行。

      解决方案:- 现在我不知道你的后台任务到底是什么。如果是AsyncTask,则在onPreExecute() 中显示进度并在onPostExecute() 中关闭它。 而且您还需要等到请求过程显示AlertDialog 在结果的最后。所以你必须使用回调。阅读Implementing a callback。

      【讨论】:

        【解决方案4】:

        你可以试试这段代码

        ProgressDialog pd = new ProgressDialog(yourActivity.this); 
        pd.setMessage("loading"); 
        pd.show();
        

        在警告对话框之前关闭进度对话框

        pd.dismiss();
        

        更多信息

        https://www.google.com/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/10446125/how-to-show-progress-dialog-in-android&ved=2ahUKEwjb4bbyy73ZAhUH66QKHQMgBtUQFjAAegQIBxAB&usg=AOvVaw3WUSL439tsqqdnbc7ED8HW

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-07
          • 1970-01-01
          • 1970-01-01
          • 2013-02-25
          • 1970-01-01
          相关资源
          最近更新 更多