1

我发布了一个问题 Progress Dialog is not displayed while getting data from different thread class 但我没有得到适当的答案。我已经使用异步任务来显示进度对话框,但它没有显示。这是示例代码

public class JsonData extends AsyncTask<String, String, String> {
private ProgressDialog mProgressDialog;
Context context;


public JsonData(Context context) 
{
        this.context=context;
     mProgressDialog = new ProgressDialog(context);
     mProgressDialog.setMessage("Loading Please Wait.");
     mProgressDialog.setIndeterminate(false);
     mProgressDialog.setMax(100);
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     mProgressDialog.setCancelable(true);
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    mProgressDialog.show();
}

@Override
protected String doInBackground(String... aurl) {
    String results="";
    try {
         int k=0;
         URL url1;
             url1 = new URL(aurl[0]);
             InputStream input=url1.openStream();
             BufferedInputStream bis=new BufferedInputStream(input);
             ByteArrayBuffer baf=new ByteArrayBuffer(1000);
             while((k=bis.read())!=-1)
             {
             baf.append((byte)k);
             }
             results=new String(baf.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return results;
}


@Override
protected void onPostExecute(String jsondata) {
   mProgressDialog.dismiss();
}
}

这是我调用异步任务的方法

 private void getRecordsByCount(final String data) {
        try {
            int color=Color.BLACK;
            tableLayoutGrid.removeAllViews();
            final String[] details = data.split("_");
            SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            String formattedDate = df.format(new Date());
            String url = ipaddress + "/GrantLeavesList?Companyid=" + user_info.get("CompanyId") + "&divisionid=" + details[3] + "&userid=" + user_info.get("userid") + "&roleid="
                    + user_info.get("RoleId") + "&Employeeid=" + user_info.get("EmployeeId") + "&leavetypeid=" + staticDetails.get(details[0]) + "&strStatus=" + staticDetails.get(details[1])
                    + "&type=" + staticDetails.get(details[2]) + "&Date=" + formattedDate;

            String url2=ipaddress + "/GrantLeavesChildList?Companyid=" + user_info.get("CompanyId") + "&divisionid=" + details[3] + "&userid=" + user_info.get("userid") + "&roleid="
                    + user_info.get("RoleId") + "&Employeeid=" + user_info.get("EmployeeId") + "&leavetypeid=" + staticDetails.get(details[0]) + "&strStatus=" + staticDetails.get(details[1])
                    + "&type=" + staticDetails.get(details[2]) + "&Date=" + formattedDate;




            JsonData jdata=new JsonData(context);
            jdata.execute(url,null,null);
            String jsonString=jdata.get();
            JSONObject obj=new JSONObject(jsonString);

            JsonData jdataChild=new JsonData(context);
            jdataChild.execute(url2,null,null);
            String jsonChildString=jdataChild.get();
            JSONObject objchild=new JSONObject(jsonChildString);



            btnGrantSubmit.setVisibility(View.GONE);
            if (obj != null) {

                leaveforwardcounts = obj.getJSONArray("Table1");
                leaveforwardchildcounts=objchild.getJSONArray("Table11");
                ScrollView scrollGrid = new ScrollView(this);
                TableRow datarow = new TableRow(this);
                datarow.setWeightSum(100);
                TableLayout table = new TableLayout(this);
                for (int i = 0; i < leaveforwardcounts.length(); i++) {
                    btnGrantSubmit.setVisibility(View.VISIBLE);
                    JSONObject record = leaveforwardcounts.getJSONObject(i);
                    String applicantname = record.getString("Applicant");
                    String toDate = record.getString("ToDate");
                    String noofdays = record.getString("NumberOfDays");
                    String LOP = record.getString("LOP");
                    if(LOP!=null && LOP.trim().length()!=0)
                    {
                        color=Color.RED;
                    }
                    final int id = i;
                    final Button gridbutton = new Button(this);
                    gridbutton.setText(status);
                    gridbutton.setTextColor(Color.BLACK);
                    gridbutton.setBackgroundResource(R.drawable.grdbutton_30x30);
                    gridbutton.setGravity(Gravity.CENTER);
                    gridbutton.setPadding(2, 0, 2, 0);
                    gridbutton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            changeRadioButtonState(gridbutton, id, data);
                        }
                    });
                    gridbutton.setOnLongClickListener(new OnLongClickListener() {

                        @Override
                        public boolean onLongClick(View v) {
                            setSelection(gridbutton);
                            return true;
                        }
                    });

                    TextView tvApplicantName = new TextView(this);

                    TextView tvToDate = new TextView(this);
                    TextView tvNoOfDays = new TextView(this);
                    TextView empty = new TextView(this);
                    TextView empty2 = new TextView(this);
                    if (applicantname.trim().length() >= 18) {
                        applicantname = applicantname.substring(0, 18);
                    }

                    tvApplicantName.setText(applicantname);
                    tvApplicantName.setTypeface(font2);
                    tvApplicantName.setWidth(70);
                    tvApplicantName.setTextColor(color);
                    tvApplicantName.setPadding(5, 0, 0, 0);

                    tvToDate.setText(toDate);
                    tvToDate.setTypeface(font2);
                    tvNoOfDays.setText(noofdays);
                    tvNoOfDays.setTypeface(font2);
                    tvNoOfDays.setGravity(Gravity.RIGHT);

                    Button ivDetails = new Button(this);
                    ivDetails.setText(" ");
                    ivDetails.setPadding(2, 0, 2, 0);
                    ivDetails.setBackgroundResource(R.drawable.detailsbutton_30x30);
                    ivDetails.setGravity(Gravity.CENTER);

                    ivDetails.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            leaveDetails = new PopupWindow(showLeaveDetails(id, leaveforwardcounts,data,leaveforwardchildcounts), (int) (width * 0.8), height / 2, true);
                            leaveDetails.showAtLocation(mainlayout, Gravity.CENTER, 0, 0);
                        }
                    });

                    TableRow row = new TableRow(this);

                    row.setPadding(0, 3, 0, 3);
                    row.setWeightSum(100);
                    row.addView(tvApplicantName, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 55));
                    row.addView(tvNoOfDays, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 5));
                    row.addView(empty2, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20));
                    row.addView(ivDetails, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
                    row.addView(empty, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
                    row.addView(gridbutton, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
                    table.addView(row);
                }
                scrollGrid.addView(table);
                datarow.addView(scrollGrid, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 100));
                tableLayoutGrid.addView(datarow);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

我需要根据来自服务的数据构建页面。在我的应用程序中,大约有 20-30 个服务..如果我使用异步任务作为内部类,它工作得很好......但是如何重用我的代码......

4

5 回答 5

2

用户,我认为您需要更好地了解使用 AsyncTask 的原因以及它提供的回调/挂钩方法的用途。

首先是原因:如果你有一个长时间运行的任务,你不能在主线程(也称为 UI 线程)上运行它,因为你的应用程序最终会显示 ANR 错误。现在,如果您的长时间运行的任务不需要在屏幕上显示输出(完成后,进度报告等),您可以很好地将它放在工作线程中并让它自己运行(甚至可能将其委托给保证运行到完成的服务,但这是另一回事)。但是,很多时候情况并非如此,您希望根据长期运行任务的结果/进度来更新 UI。为此,您必须以某种方式分支一个线程并在那里完成工作,但是,由于您只能从主线程操作 UI,因此您必须在完成后将结果发回主线程。

这是我们转向 AsyncTask 及其钩子方法的地方。AsyncTask 实际上只是一个实用程序类,它可以帮助您完全按照上面的说明进行操作:将您的工作放在单独的线程上,并在完成时在主线程上获得回调(并且结果可用)。检查文档你会发现:

onPreExecute():保证在主线程上运行。允许您在工作开始之前做一些事情(例如显示进度对话框)。

doInBackground():保证在后台线程上运行。你在这里长期运行的东西。

onPostExecute():保证在 doInBackground() 完成后在主线程上运行。你的任务结果现在可用,你可以用它做一些事情(比如把它放在屏幕上)。

回到您对 .get() 方法有问题的建议:由于您在 AsyncTask 上调用 .execute() 并在之后立即对结果进行 .get()-ing,因此后台作业可能尚未完成。相反,您应该做任何您想做的事情,从 AsyncTask 的 onPostExecute 中的 .get() 开始。因此,如果您的任务下载了一个图像,并且您想在它运行时向用户显示“正在下载”消息,您应该执行以下操作:

//pseudo code
void exampleButtonClicked() {
  new AsyncImageDownloader.execute();
}

class AsyncImageDownloader extends AsyncTask {
  onPreExecute() {
    show "downloading";
  }

  doInBackground() {
    downloadImg();
  }

  onPostExecute() {
    hide "downloading";
    put downloaded img on ImageView;
  }
}
//end of pseudo code

希望这会有所帮助.. 不会编写你的答案,因为那样你就什么也学不到了 ;-)

干杯!

于 2012-12-20T09:29:21.810 回答
2

您不需要为 postExecute 启动后台方法。正如@baske 所写,.get() 有问题 - 即使您使用的是 AsyncTask,它也会阻塞您的线程。尝试与链接问题相关的问题,因此仅将YourActivityClass作为参数添加到 JsonData 的构造器中

public JsonData(YourActivityClass activity) 
{
    this.activity=activity;
    mProgressDialog = new ProgressDialog(activity);

}
protected void onPostExecute(String jsondata) {
    if (mProgressDialog != null || mProgressDialog.isShowing()){
        mProgressDialog.dismiss();
    }
    if(jsondata!=null) {
        activity.yourcallback(jsondata)
    }

}

并在YourActivityClass中定义yourcallback()

private void yourcallback(String data) {
    jsonRecordsData=data;
    showRecordsFromJson();

}
于 2013-01-02T17:46:30.997 回答
0

您只能从 UI 线程执行 UI 操作。尝试在 UI 线程上运行它。

runOnUiThread(new Runnable() {

        public void run() {
            mProgressDialog.show();
        }
    });
于 2012-12-20T06:17:53.027 回答
0

尝试以下操作:

 @Override
   protected void onPreExecute() 
  {

 mProgressDialog =ProgressDialog.show(GmailInbox.this, "", "Please Wait",true,false);
 super.onPreExecute();
  }
于 2012-12-20T06:19:37.220 回答
0

您可以覆盖方法 onPreExecute() 并为此代码实现,

@Override
    protected void onPreExecute() {
        super.onPreExecute();
        ProgressDialog mProgressDialog = ProgressDialog.show(ActivityName.this, "Wait", "Loading....");
    }

和 onPostExecute() 方法实现和关闭对话框,

@Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (mProgressDialog != null || mProgressDialog.isShowing())
            mProgressDialog.dismiss();
    }
于 2012-12-20T06:25:03.000 回答