-1

In Screen have Button. Once Use click on Button an AsyncTask will execute and fetch the data from database and show in the AlertDialog. Between ButtonClick and AlertDialog time needs to show CircularProgressBar.

My code is written below but Progress bar is not showing.

Any other workaround for the requirement.

 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();
    }

}

I have update the code ProgressDialog code into Async task like below but still progress dialog is not appearing.

      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();


}

}

In Maintask calling async task like below

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>();

Progress bar screen not appearing.

Kumar
  • 21
  • 5

4 Answers4

0

How is the ProgressDialogsuppose to Visible. You initialize and dismiss() it inside same block . It will dismiss instantly after initialization .

See the Code below .

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

Here residentsPaymentInfo seems to be a AsyncTask or a Executor ultimately a background thread . So this will run on other thread and you code which is 'progressDialog.dismiss()' get executes right after initialization .

Solution :- Right now i have no idea what exactly your background task is . If its AsyncTask then show the progress in onPreExecute() and dismiss it in onPostExecute(). And you also need to wait until the request process to show the AlertDialog at the end of result. So you have to use a callback . Read Implementing a callback.

ADM
  • 20,406
  • 11
  • 52
  • 83
0

This is not directly change your code, but give u a example. Put your logical in Thread.runnable, then after finish your work, dismiss 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();
    }
forqzy
  • 389
  • 2
  • 11
0

AsyncTask never block your UI thread,it run in background.

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

here you have directly call the dismiss() method,it will not wait for completion of getResidentsPaymentMonthDetails it directly dismiss the dialog also residentsPaymentInfo is also null or blank.

you can display the dialog in 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();

            }

         }
MJM
  • 5,119
  • 5
  • 27
  • 53
  • I have change code to call ProgressDialog from Async task. But sitll the Progress Dialog not showing. – Kumar Feb 24 '18 at 06:57
-1

You can try with this code

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

Dismiss the progress dialog before alert dialog

pd.dismiss();

For further information

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

Fazal Hussain
  • 1,129
  • 12
  • 28