简体   繁体   English

Android应用程序中的ProgressDialog

[英]ProgressDialog in android app

I have a problem with my app. 我的应用程序有问题。 The progressDialog shows perfectly but after that the aplication doesn't work. progressDialog可以完美显示,但是此后应用将不起作用。 The app have to show a message after the progressDialog and complete some editText. 该应用程序必须在progressDialog之后显示一条消息,并完成一些editText。 Here is the code of the MyActivity: 这是MyActivity的代码:

public class MyActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    Button button = (Button) findViewById(R.id.searchBtn);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
        final ProgressDialog progress = ProgressDialog.show(MyActivity.this,             

          "Buscando...",
                    "Espere mientras se busca la información...", true);

            new Thread(new Runnable() {
                @Override
                public void run()
                {
                    // Código principal de la aplicación

                    EditText text = (EditText) findViewById(R.id.nameTxt);
                    //comprobar si existe nombre
                    if ("".equals(text.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.noNameMsg), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String enteredName = text.getText().toString();
                    String finalName = enteredName.toLowerCase();
                    //String salutation = getResources().getString(R.string.hello)
                    // + " " + enteredName;
                    int codeASCII = 0;
                    for (int x = 0; x < finalName.length(); x++) {
                        codeASCII += (int) finalName.charAt(x);
                    }


                    EditText day = (EditText) findViewById(R.id.day);
                    //comprobar si se ha introducido día
                    if ("".equals(day.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.noDayMsg), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    EditText month = (EditText) findViewById(R.id.month);
                    //comprobar si se ha introducido mes
                    if ("".equals(month.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.noMonthMsg), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    EditText year = (EditText) findViewById(R.id.year);
                    //comprobar si se ha introducido año
                    if ("".equals(year.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.noYearMsg), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    int dia = Integer.valueOf(day.getText().toString());
                    int año = Integer.valueOf(year.getText().toString());
                    int mes = Integer.valueOf(month.getText().toString());
                    int nacimiento = dia + mes + año;
                    int nTotal = 17;
                    int x = (codeASCII + nacimiento) % nTotal;

                    String[] insultos = new String[nTotal];

                    insultos[0] = "No te preocupes, hay más virtudes que la inteligencia";
                    insultos[1] = "Tienes futuro como plantador de nabos";
                    insultos[2] = "Ha llegado la hora de pensar en ir saliendo del armario";
                    insultos[3] = "Se puede vivir con dignidad a pesar de tan elevado grado de alopecia";
                    insultos[4] = "Tú tambien podrás triunfar, recuerda a Forrest Gump";
                    insultos[5] = "Ni Newton ni Einsten, sabemos que lo tuyo es Bob Esponja";
                    insultos[6] = "A no todo el mundo le sale bien una O cuando usa un canuto. No te preocupes, ya aprenderás";
                    insultos[7] = "Tu atractivo será evidente para muchos, puede incluso que para alguna persona";
                    insultos[8] = "No es un error que te creas tan atractivo, tu error es que no estás bien informado";
                    insultos[9] = "Te espera un brillante fututro en el mundo del porno, siempre hace falta gente que lleve las toallas";
                    insultos[10] = "Tu cociente intelectual es, bueno, el suficiente para que te hayas descargado esta aplicación absolutamente inútil";
                    insultos[11] = "Muéstrate siempre tal y como eres, salvo cuando intentes gustar a alguien";
                    insultos[12] = "Si le caes bien a mucha gente deberías recordar que el perro es el mejor amigo del hombre ";
                    insultos[13] = "Tienes una mente de altos vuelos, o lo que es lo mismo, un cerebro de pájaro";
                    insultos[14] = "La mediocridad es lo que más abunda, puede que eso te dé consuelo";
                    insultos[15] = "Totorota es una palabra canaria. Aún así, cualquier peninsular que te vea sabrá lo que significa";
                    insultos[16] = "Por fin podrás vivir como siempre habías soñado... en casa de tu madre";

                    TextView out = (TextView) findViewById(R.id.out);
                    out.setText(insultos[x]);


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run()
                        {
                            progress.dismiss();
                        }
                    });
                }
            }).start();
        }

    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

} }

you can use AsyncTask class to do something like this: 您可以使用AsyncTask类执行以下操作:

after onCreate() method define inner class like below code: 在onCreate()方法定义内部类之后,如下代码:

private class Async extends AsyncTask<String, Integer, String> {

    ProgressDialog progressDialog ;

    protected String doInBackground(String... urls) {

                String enteredName = text.getText().toString();
                String finalName = enteredName.toLowerCase();
                //String salutation = getResources().getString(R.string.hello)
                // + " " + enteredName;
                int codeASCII = 0;
                for (int x = 0; x < finalName.length(); x++) {
                    codeASCII += (int) finalName.charAt(x);
                }




                int dia = Integer.valueOf(day.getText().toString());
                int año = Integer.valueOf(year.getText().toString());
                int mes = Integer.valueOf(month.getText().toString());
                int nacimiento = dia + mes + año;
                int nTotal = 17;
                int x = (codeASCII + nacimiento) % nTotal;

                String[] insultos = new String[nTotal];

                insultos[0] = "No te preocupes, hay más virtudes que la inteligencia";
                insultos[1] = "Tienes futuro como plantador de nabos";
                insultos[2] = "Ha llegado la hora de pensar en ir saliendo del armario";
                insultos[3] = "Se puede vivir con dignidad a pesar de tan elevado grado de alopecia";
                insultos[4] = "Tú tambien podrás triunfar, recuerda a Forrest Gump";
                insultos[5] = "Ni Newton ni Einsten, sabemos que lo tuyo es Bob Esponja";
                insultos[6] = "A no todo el mundo le sale bien una O cuando usa un canuto. No te preocupes, ya aprenderás";
                insultos[7] = "Tu atractivo será evidente para muchos, puede incluso que para alguna persona";
                insultos[8] = "No es un error que te creas tan atractivo, tu error es que no estás bien informado";
                insultos[9] = "Te espera un brillante fututro en el mundo del porno, siempre hace falta gente que lleve las toallas";
                insultos[10] = "Tu cociente intelectual es, bueno, el suficiente para que te hayas descargado esta aplicación absolutamente inútil";
                insultos[11] = "Muéstrate siempre tal y como eres, salvo cuando intentes gustar a alguien";
                insultos[12] = "Si le caes bien a mucha gente deberías recordar que el perro es el mejor amigo del hombre ";
                insultos[13] = "Tienes una mente de altos vuelos, o lo que es lo mismo, un cerebro de pájaro";
                insultos[14] = "La mediocridad es lo que más abunda, puede que eso te dé consuelo";
                insultos[15] = "Totorota es una palabra canaria. Aún así, cualquier peninsular que te vea sabrá lo que significa";
                insultos[16] = "Por fin podrás vivir como siempre habías soñado... en casa de tu madre";

          return insultos[x];


    }

    @Override
    protected void onPreExecute() {

        progressDialog = new ProgressDialog(yourActivity.this);
        progressDialog.setMessage("yourMessage");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog .dismiss();
        outt.setText(result);
    }
}  

define this variable as global variable: 将此变量定义为全局变量:

    EditText text
    EditText day;
    EditText month;
    EditText year;
    TextView outt;  

in onCreate() : 在onCreate()中:

 text = (EditText) findViewById(R.id.nameTxt);
 day = (EditText) findViewById(R.id.day);
 month = (EditText) findViewById(R.id.month);
 year = (EditText) findViewById(R.id.year);
 outt = (TextView) findViewById(R.id.out);
 if ("".equals(text.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.noNameMsg), Toast.LENGTH_SHORT).show();
}else if ("".equals(day.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.noDayMsg), Toast.LENGTH_SHORT).show();
}else if ("".equals(month.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.noMonthMsg), Toast.LENGTH_SHORT).show();
} else  if ("".equals(year.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.noYearMsg), Toast.LENGTH_SHORT).show();
}else{
        new Async.execute();
}

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

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