简体   繁体   English

从Activity调用时,另一个AsyncTask类中的ProgressDialog不显示

[英]ProgressDialog in another AsyncTask class not showing when called from Activity

I have a class called RestClient that gets some information from my webService and then return and I'm trying to make a Progress dialog run while it is accessing the internet. 我有一个名为RestClient的类,该类从我的webService中获取一些信息,然后返回,而我正在尝试使Progress对话框在访问Internet时运行。 And as I use this class in more than one place I won't make in the Activity itself. 而且,由于我在多个地方使用了此类,所以我不会在Activity本身中做任何事情。 Here is my RestClient class: 这是我的RestClient类:

public class RestClient extends AsyncTask<URL, String, String> {

    private Context context;
    private String string;
public RestClient(Context context, String string)
{
    this.context = context;
    this.string = string;
}

@Override
protected void onPreExecute() {
    dialog = ProgressDialog.show(context, "Buscando seu Produto","Por favor, espere um momento...",true ,false);
    //I've already tried:
    /*ProgressDialog dialog = new ProgressDialog(context);
    dialog.setTitle("Buscando seu Produto");
    dialog.setMessage("Por favor, espere um momento...");
    dialog.setIndeterminate(true);
    dialog.setCancelable(false);*/

    dialog.show();
    super.onPreExecute();
}

@Override
protected String doInBackground(URL... params) {
    try {

        //Some WebService gets and Json conversions using my string variable
        //and some Thread.sleep that counts 2000 miliseconds to do all the queries

        dialog.dismiss();

    } catch (IOException | InterruptedException |JSONException e) {
        e.printStackTrace();

        dialog.dismiss();

        return e.getMessage();
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);


   }
}

And in my activity I call the class RestClient when I click a button like this: 在我的活动中,当我单击如下按钮时,我将调用RestClient类:

--- EDIT : I forgot to mention that I have an AlertDialog in this same activity that CAN be shown sometimes before and after the ProgressDialog --- ---编辑:我忘了提到我在同一活动中有一个AlertDialog,有时可以在ProgressDialog之前和之后显示-

private Button buttonConfirm;
     private EditView evString;

     private String theString;
     private String returnFromExecute;

     private RestClient restClient;


     private AlertDialog.Builder dialog;

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_access_webservice);

            evString = (EditText) findViewById(R.id.editViewMyString);
            buttonConfirm = (Button) findViewById(R.id.buttonConfirm);

            dialog = new ProgressDialog(IdentificacaoDeProdutoActivity.this);
            dialog.setTitle("Error");
            dialog.setMessage("Please try again");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);


            buttonConfirmar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)  {                  
                    theString = evString.getText().toString();
                    if(!(theString!=null && theString.trim().length()>0)) //To check if theString is not null
                    {
                          dialog.show();
                    }

                    restClient = new RestClient(AccessWebserviceActivity.this, theString);

                    //Then I call execute and put a Thread.sleep a bit longer to compensate the ones I have in my doInBackground
                    restClient.execute();
                    try {
                        Thread.sleep(2050);

                    } catch (Exception e) {
                        dialog.show();
                        return;
                    }
                }
            }
        }

The problem is that my ProgressDialog never shows. 问题是我的ProgressDialog从不显示。 I've already tried getParent() , getApplication() and getApplicationContext() instead of AccessWebserviceActivity.this but none have worked. 我已经尝试过getParent()getApplication()getApplicationContext()而不是AccessWebserviceActivity.this但是都没有用。 Someone Have any idea what is happening and what should I do? 有人知道发生了什么,该怎么办?

you have not created progress dialog try this. 您尚未创建进度对话框,请尝试此操作。

ProgressDialog dialog;

 @Override
    protected void onPreExecute() {
        dialog= new ProgressDialog(context);
        dialog.setMessage("on Progress");
        dialog.show();
        super.onPreExecute();
    }

You need to call 你需要打电话

dialog = ProgressDialog.show(context, "Buscando seu Produto","Por favor, espere um momento...",true ,false);

and remove 并删除

 dialog.show();

Also put your dialog.dismiss() ; 还把你的dialog.dismiss() ; method in onPostExecute (). onPostExecute ()中的方法。 This dialog.dismiss() method is good in catch block but what's its purpose if you are calling this method in try block. 这个dialog.dismiss()方法在catch块中很好,但是如果在try块中调用此方法,它的目的是什么。 It will remove progress dialog as soon as you call this AsyncTask . 一旦调用此AsyncTask ,它将删除进度对话框。

returnFromExecute = restClient.get();

Remove that statement. 删除该语句。 You have already: 您已经:

restClient.execute();

That should do. 那应该做。

The result of doInBackground() you should handle in onPostExecute() . 结果doInBackground()你应该在处理onPostExecute() It cannot be handled or retrieved in onCreate() . 无法在onCreate()处理或检索它。

After a lot of researches about Threads and Process I found out that I had to encapsulate the all the code I have after my RestClient.execute in a 经过大量关于线程和进程的研究,我发现必须将RestClient.execute之后的所有代码封装在一个

new Thread(new Runnable() { public void run() { // My code } });

so that the execution of the code happened in background as well as the WebService query. 这样代码的执行就在后台以及WebService查询中进行。

EDIT: 编辑:

Even if creating a new Thread works, it is not recommended! 即使创建新线程可行,也不建议这样做! The right thing to do would be to create another class that extends AsyncTask to do job. 正确的做法是创建另一个扩展AsyncTask来完成工作的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM