本文介绍了不能用的AsyncTask显示ProgressDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要显示一个ProgressDialog在等待服务器的响应。

I want to show a ProgressDialog while waiting for server's response.

我的类JogarActivity执行以下操作(我的应用程序是一个问答游戏):

My class JogarActivity does the following (My app is a quiz game):

1初始化变量

2 - 验证,如果它是与否的第一个问题(primeiraPergunta)

2- Verify if it is or not the first question (primeiraPergunta)

2.1-如果这是第一个问题,调用UserFunctions.getJogar()。此功能建立与参数的列表,并将其发送到JSONParser类。 JSONParser使得http请求并返回数据的JSONArray

2.1- If it's the first question, calls UserFunctions.getJogar(). This function build an list with parameters and send it to a JSONParser class. JSONParser makes the http request and returns a JSONArray with data

2.2-如果它不是第一个问题,刚才检索意图演员的实际问题。

2.2- If it isn't the first question, just retrieve the actual question from intent extras.

3尝试解析JSONArray字符串。如果用户已经回答了实际的类别中的所有问题,这将返回一个异常(JSONArray为null),所以它可以显示一个对话框,要求用户选择其他类别。

3- Try to parse JSONArray to string. If the user had already answered all questions in the actual category, this will return an Exception (JSONArray will be null), so it can show a dialog asking user to select another category.

4-提出在屏幕上的所有数据(问题,答案选项),并等待用户的交互。

4- Puts all data (question and answer options) on screen and wait for user's interaction.

5。当用户选择一个答案,它调用UserFunctions.gerResposta()。这一次,它会更新数据库后返回一个状态消息(正确的,错误的,错误等)(标点符号,回答问题等)。它也将检索下一个问题。

5- When user select an answer, it calls UserFunctions.gerResposta(). This time, it will return a status message (correct, wrong, error, etc) after updating the database (ponctuation, answered questions etc). It will also retrieve the next question.

6显示有关的问题和一个OK按钮,当pressed,重新启动活动信息的对话框。接下来的问题是为intent.putExtra()和primeiraPergunta(第一个问题?)被设置好的假。通过

6- Show a dialog with info about the question and an OK button that, when pressed, restarts the activity. The next question is passed as intent.putExtra(), and primeiraPergunta (first question?) is setted to false.

* UserFunctions和JSONParser不活动,所以我不能使用ProgressDialog在他们里面,只要我无法检索应用程序的上下文。
* JSONParser被其他类使用,所以我preFER不改变它
*我正在寻找另一种解决方案比JogarActivity重写everithing(将做出必要的改变其他类也是如此)。

*UserFunctions and JSONParser are not activities, so I can't use ProgressDialog inside them, as long as I can't retrieve application's context.*JSONParser is used by other classes, so I prefer not to changing it*I'm looking for another solution than rewriting everithing in JogarActivity (that will make necessary to change other classes too).

第一下面我粘贴JogarActivity没有变化。于是,我试着添加的AsyncTask显示ProgressDialog,但它只是不会出现在屏幕上(AsyncTask.get()是用来做JogarActivity等待AsyncTask的结果)。 Finnaly,我已经粘贴另一个类(RegisterActivity),其中AsyncTask的工作就好了。

first below i've pasted JogarActivity without changes. Then, I've tried to add an AsyncTask to show the ProgressDialog, but it just doesn't appears on screen (AsyncTask.get() is used to make JogarActivity wait for results from asynctask). Finnaly, i've pasted another class (RegisterActivity) where the AsyncTask works just fine.

我猜AsyncTask的可能不是最好的方法,但我只是想早点工作越好。这不是我的code(除RegisterActivity)。应用工程后,我会优化它:)

I guess AsyncTask is probably not the best approach, but I just want to make it works as soon as possible. This is not my code (except for RegisterActivity). After the app works i'll optimize it :)

========== JogarActivity.java ====================

==========JogarActivity.java====================

public class JogarActivity  extends Activity {

private static final String TAG_RESPOSTA = "resposta";
private static final String TAG_ID = "idt";
private static final String TAG_PRIMEIRAPERGUNTA = "primeiraPergunta";
private static final String TAG_JSON = "json";
private Integer idPergunta;
private String pergunta;
private String respostaRecebe; //Texto da resposta que o usuário escolheu
private String respostaConfere;
private String resposta;
private String idCategoria;
private String respostaCorreta;
private String[] arrayRespostas = new String[5];
private boolean primeiraPergunta;
private JSONArray json;
private JSONArray jsonResposta;
String idUser;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);





    setContentView(R.layout.jogar_layout);
    Intent in = getIntent();
    String url = this.getString(R.string.urlSite);
    ArrayList<HashMap<String, String>> respostaList = new ArrayList<HashMap<String, String>>();

    String idt = in.getStringExtra(TAG_ID);
    primeiraPergunta = in.getBooleanExtra(TAG_PRIMEIRAPERGUNTA, true);

    TextView insertPergunta = (TextView) findViewById(R.id.insertPergunta);
    ListView insertRespostas = (ListView) findViewById(R.id.listResposta);

    SharedPreferences settings = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
    Integer idUsuario = settings.getInt("idUsuario", 0);
    idUser = idUsuario.toString();


    if (primeiraPergunta){
        UserFunctions userFunction = new UserFunctions();
        json = userFunction.getJogar(idt, idUser);

    }else{
        try {
            json = new JSONArray(in.getStringExtra(TAG_JSON));
            json = json.getJSONArray(2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }




    try{
        @SuppressWarnings("unused")
        String s = json.toString(); // Se o usuário já respondeu todas as perguntas da categoria, retorna uma Exception
        try {
            idPergunta = json.getInt(0);
            pergunta = json.getString(1);
            for (int i=2; i<7 ; i++){
                resposta = json.getString(i);
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(TAG_RESPOSTA, resposta);
                respostaList.add(map);
                arrayRespostas[i-2] = resposta;
            }

            respostaCorreta = json.getString(7);
            respostaConfere = arrayRespostas[Integer.parseInt(respostaCorreta)-1];
            idCategoria = json.getString(11);



        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        insertPergunta.setText(pergunta);
        ListAdapter adapter = new SimpleAdapter(this, respostaList,
                R.layout.resposta_data,
                new String[] { TAG_RESPOSTA }, new int[] {
                        R.id.insertResposta });

        insertRespostas.setAdapter(adapter);



        // selecting single ListView item
        ListView lv = insertRespostas;


        lv.setOnItemClickListener(new OnItemClickListener() {



            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){

                Integer pos = position + 1;
                String respostaEscolhida = pos.toString();
                String pergunta = idPergunta.toString();

                UserFunctions userFunction = new UserFunctions();
                            final JSONArray jsonResposta = userFunction.getResposta(pergunta, idUser , respostaEscolhida, idCategoria);



                respostaRecebe = arrayRespostas[position];

                String mensagem = "";
                try {
                    mensagem = jsonResposta.getString(1);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                final String jrString = jsonResposta.toString();

                AlertDialog alertDialog = new AlertDialog.Builder(
                        JogarActivity.this).create();


                    if (respostaCorreta.equals(pos.toString())){
                        alertDialog.setTitle("PARABÉNS");
                        alertDialog.setMessage("Resposta correta: "+respostaRecebe+"\n\n"+mensagem);
                    }
                    else{
                        alertDialog.setTitle("VOCÊ ERROU");
                        alertDialog.setMessage("Sua resposta: "+respostaRecebe+"\n\nResposta correta: "+respostaConfere+"\n\n"+mensagem);

                    }
                        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent i = new Intent(getApplicationContext(),JogarActivity.class);
                                //in.putExtra(TAG_NAME, name);
                                i.putExtra(TAG_ID, idCategoria);
                                i.putExtra(TAG_PRIMEIRAPERGUNTA, false);
                                i.putExtra(TAG_JSON, jrString);
                                startActivity(i);
                                finish();
                            }
                    });

                    alertDialog.show();

                        }


        });
    }catch (Exception e){
        AlertDialog sem_perguntas = new AlertDialog.Builder(
                JogarActivity.this).create();
            sem_perguntas.setTitle("PARABÉNS");
            sem_perguntas.setMessage("Você já respondeu todas as perguntas desta categoria!");

            sem_perguntas.setButton("VOLTAR", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(getApplicationContext(),CategoriasJogarActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        startActivity(i);
                        finish();
                    }
            });

            sem_perguntas.show();
            //finish();
    }



   //finish();
}


public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.layout.menu_jogar, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item)
{

    switch (item.getItemId())
    {
    case R.id.menu_pularPergunta:
        Intent i = new Intent(getApplicationContext(),JogarActivity.class);
        startActivity(i);
        finish();
        Toast.makeText(JogarActivity.this, "Pergunta Pulada", Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}

}

============== JogarActivity用的AsyncTask(ProgressDialog不出现)=============

==============JogarActivity with AsyncTask (ProgressDialog doesn't appears)=============

public class JogarActivity  extends Activity {

private static final String TAG_RESPOSTA = "resposta";
private static final String TAG_ID = "idt";
private static final String TAG_PRIMEIRAPERGUNTA = "primeiraPergunta";
private static final String TAG_JSON = "json";
private Integer idPergunta;
private String pergunta;
private String respostaRecebe; //Texto da resposta que o usuário escolheu
private String respostaConfere;
private String resposta;
private String idCategoria;
private String respostaCorreta;
private String[] arrayRespostas = new String[5];
private boolean primeiraPergunta;
private JSONArray json;
private JSONArray jsonResposta;
ProgressDialog pDialog;
Context ctx = this;
String idUser;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);





    setContentView(R.layout.jogar_layout);
    Intent in = getIntent();
    String url = this.getString(R.string.urlSite);
    ArrayList<HashMap<String, String>> respostaList = new ArrayList<HashMap<String, String>>();

    String idt = in.getStringExtra(TAG_ID);
    primeiraPergunta = in.getBooleanExtra(TAG_PRIMEIRAPERGUNTA, true);

    TextView insertPergunta = (TextView) findViewById(R.id.insertPergunta);
    ListView insertRespostas = (ListView) findViewById(R.id.listResposta);

    SharedPreferences settings = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
    Integer idUsuario = settings.getInt("idUsuario", 0);
    idUser = idUsuario.toString();


    if (primeiraPergunta){
        //UserFunctions userFunction = new UserFunctions();
        //json = userFunction.getJogar(idt, idUser);
        AsyncTask jogar = new Jogar().execute("url", "http://www.qranio.com/mobile/perguntas.php", "categoria", idt, "idUsuario", idUser);
        try {
            json = (JSONArray) jogar.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }else{
        try {
            json = new JSONArray(in.getStringExtra(TAG_JSON));
            json = json.getJSONArray(2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }




    try{
        @SuppressWarnings("unused")
        String s = json.toString(); // Se o usuário já respondeu todas as perguntas da categoria, retorna uma Exception
        try {
            idPergunta = json.getInt(0);
            pergunta = json.getString(1);
            for (int i=2; i<7 ; i++){
                resposta = json.getString(i);
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(TAG_RESPOSTA, resposta);
                respostaList.add(map);
                arrayRespostas[i-2] = resposta;
            }

            respostaCorreta = json.getString(7);
            respostaConfere = arrayRespostas[Integer.parseInt(respostaCorreta)-1];
            idCategoria = json.getString(11);



        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        insertPergunta.setText(pergunta);
        ListAdapter adapter = new SimpleAdapter(this, respostaList,
                R.layout.resposta_data,
                new String[] { TAG_RESPOSTA }, new int[] {
                        R.id.insertResposta });

        insertRespostas.setAdapter(adapter);



        // selecting single ListView item
        ListView lv = insertRespostas;


        lv.setOnItemClickListener(new OnItemClickListener() {



            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){




                Integer pos = position + 1;
                String respostaEscolhida = pos.toString();
                String pergunta = idPergunta.toString();



                //UserFunctions userFunction = new UserFunctions();
                //final JSONArray jsonResposta = userFunction.getResposta(pergunta, idUser , respostaEscolhida, idCategoria);
                AsyncTask jogar = new Jogar().execute("url", "http://www.qranio.com/mobile/resposta.php", "id_pergunta", pergunta, "id_usuario", idUser, "resposta", respostaEscolhida, "categoria", idCategoria);

                try {
                    jsonResposta = (JSONArray) jogar.get();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                } catch (ExecutionException e1) {
                    e1.printStackTrace();
                }


                respostaRecebe = arrayRespostas[position];

                String mensagem = "";
                try {
                    mensagem = jsonResposta.getString(1);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                final String jrString = jsonResposta.toString();

                AlertDialog alertDialog = new AlertDialog.Builder(
                        JogarActivity.this).create();


                    if (respostaCorreta.equals(pos.toString())){
                        alertDialog.setTitle("PARABÉNS");
                        alertDialog.setMessage("Resposta correta: "+respostaRecebe+"\n\n"+mensagem);
                    }
                    else{
                        alertDialog.setTitle("VOCÊ ERROU");
                        alertDialog.setMessage("Sua resposta: "+respostaRecebe+"\n\nResposta correta: "+respostaConfere+"\n\n"+mensagem);

                    }
                        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent i = new Intent(getApplicationContext(),JogarActivity.class);
                                //in.putExtra(TAG_NAME, name);
                                i.putExtra(TAG_ID, idCategoria);
                                i.putExtra(TAG_PRIMEIRAPERGUNTA, false);
                                i.putExtra(TAG_JSON, jrString);
                                startActivity(i);
                                finish();
                            }
                    });

                    alertDialog.show();

                        }


        });
    }catch (Exception e){
        AlertDialog sem_perguntas = new AlertDialog.Builder(
                JogarActivity.this).create();
            sem_perguntas.setTitle("PARABÉNS");
            sem_perguntas.setMessage("Você já respondeu todas as perguntas desta categoria!");

            sem_perguntas.setButton("VOLTAR", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(getApplicationContext(),CategoriasJogarActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        startActivity(i);
                        finish();
                    }
            });

            sem_perguntas.show();
            //finish();
    }



   //finish();
}

/*public void colocaResposta (int i, JSONArray json, ArrayList respostaList) throws JSONException{
    resposta = json.getString(i);
    HashMap<String, String> map = new HashMap<String, String>();
    map.put(TAG_RESPOSTA, resposta);
    respostaList.add(map);
}*/





public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.layout.menu_jogar, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item)
{

    switch (item.getItemId())
    {
    case R.id.menu_pularPergunta:
        Intent i = new Intent(getApplicationContext(),JogarActivity.class);
        startActivity(i);
        finish();
        Toast.makeText(JogarActivity.this, "Pergunta Pulada", Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}


class Jogar extends AsyncTask<String, Void, JSONArray>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ctx);
        pDialog.setMessage("Aguarde...");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected JSONArray doInBackground(String... values) {
        String url = values[1];
        int count = values.length;
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (int i=2; i<count; i++){
            params.add(new BasicNameValuePair(values[i], values[i+1]));
            i++;
        }

    JSONParser jsonParser = new JSONParser();
    JSONArray json = jsonParser.getJSONFromUrl(url, params);

        return json;
    }

    protected void onPostExecute(JSONArray result) {
        // dismiss the dialog once done

        pDialog.dismiss();
    }

}

}

================= RegisterActivity(正常工作)======================

=================RegisterActivity (Works fine)======================

public class RegisterActivity extends Activity{
EditText reg_fullname;
EditText reg_email;
EditText reg_login;
EditText reg_password;
EditText reg_password2;
Spinner reg_country;
Spinner reg_genre;
EditText reg_birthday;
EditText reg_promocode;
Button btnRegister;
Context ctx = this;
ProgressDialog pDialog;
JSONArray json;
String status;
String msg;

String fullname;
String email;
String login;
String password;
String password2;
String country;
String genre;
String birthday;
String promocode;

boolean finishActivity = false;

/**
 * @see android.app.Activity#onCreate(Bundle)
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.register);

    TextView loginScreen = (TextView) findViewById(R.id.link_to_login);

    loginScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
                            // Closing registration screen
            // Switching to Login Screen/closing register screen
            finish();
        }
    });

    reg_fullname = (EditText) findViewById(R.id.reg_fullname);
    reg_email = (EditText) findViewById(R.id.reg_email);
    reg_login = (EditText) findViewById(R.id.reg_login);
    reg_password = (EditText) findViewById(R.id.reg_password);
    reg_password2 = (EditText) findViewById(R.id.reg_password2); //confirmação de senha
    reg_country = (Spinner) findViewById(R.id.reg_country);
    reg_genre = (Spinner) findViewById(R.id.reg_genre);
    reg_birthday = (EditText) findViewById(R.id.reg_birthday);
    reg_promocode = (EditText) findViewById(R.id.reg_promocode);

    btnRegister = (Button) findViewById(R.id.btnRegister);


    btnRegister.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            fullname = reg_fullname.getText().toString();
            email = reg_email.getText().toString();
            login = reg_login.getText().toString();
            password = reg_password.getText().toString();
            password2 = reg_password2.getText().toString();
            country = reg_country.getSelectedItem().toString();
            genre = reg_genre.getSelectedItem().toString();
            birthday = reg_birthday.getText().toString();
            promocode = reg_promocode.getText().toString();

            boolean validation = true;
            String message = "Campo de preencimento obrigatório";

            if(fullname.equalsIgnoreCase("")){
                reg_fullname.setError(message);
                validation = false;
            }
            if(email.equalsIgnoreCase("")){
                reg_email.setError(message);
                validation = false;
            }
            if(!email.matches(".*@.*")){
                reg_email.setError("O endereço de email não é válido");
                validation = false;
            }
            if(login.equalsIgnoreCase("")){
                reg_login.setError(message);
                validation = false;
            }
            if(password.equalsIgnoreCase("")){
                reg_password.setError(message);
                validation = false;
            }
            if(password2.equalsIgnoreCase("")){
                reg_password2.setError(message);
                validation = false;
            }
            if(!password.equals(password2)){
                reg_password2.setError("A confirmação de senha não confere");
                validation = false;
            }
            if(birthday.equalsIgnoreCase("")){
                reg_birthday.setError(message);
                validation = false;
            }
            SimpleDateFormat bd = new SimpleDateFormat("dd/MM/yyyy");
            if(bd.parse(birthday, new ParsePosition(0)) == null){
                reg_birthday.setError("Esta data não é válida! Preencha novamente, usando o formato dd/mm/aaaa");
                validation = false;
            }

            if(validation){
            new Register().execute();
            }

        }
    });



}


class Register extends AsyncTask<Void, Void, JSONArray>{

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(ctx);
    pDialog.setMessage("Aguarde...");
    pDialog.setIndeterminate(true);
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected JSONArray doInBackground(Void... params) {
    UserFunctions userFunction = new UserFunctions();
    json = userFunction.newUser(fullname, email, login, password, country, genre, birthday, promocode);

    return json;

}

protected void onPostExecute(JSONArray result) {
    // dismiss the dialog once done
    pDialog.dismiss();
    final AlertDialog alertDialog = new AlertDialog.Builder(
            RegisterActivity.this).create();

            try {
                status = json.getString(0);
                msg = json.getString(1);
                Log.d("Status", status);
            } catch (JSONException e) {
                Log.e("RegisterActiviry", "Error converting result " + e.toString());
                e.printStackTrace();
                status = null;
            }

            if (status.equalsIgnoreCase("erro")){
                alertDialog.setTitle("Erro");
                alertDialog.setMessage(msg);

            }else if (status.equalsIgnoreCase("sucesso")){
                alertDialog.setTitle("Sucesso!");
                alertDialog.setMessage(msg);
                finishActivity = true;
            }else{
                alertDialog.setTitle("Erro");
                alertDialog.setMessage("Não foi possível realizar seu cadastro, tente novamente mais tarde.");
            }


            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if(finishActivity){
                    finish();
                    }else{
                        alertDialog.dismiss();
                    }
                }
        });

        alertDialog.show();

}

}

}

推荐答案

把你对话框如下图所示,我希望它会工作。

put you dialog like below I hope it will work.

runOnUiThread(new Runnable() {
                    public void run() {

                   //Your dailog

                    }
                });

这篇关于不能用的AsyncTask显示ProgressDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:23