2014-08-31 5 views
0

У меня проблема с моим приложением. ProgressDialog отлично показывает, но после этого приложение не работает. Приложение должно показать сообщение после progressDialog и завершить некоторый editText. Вот код MyActivity:ProgressDialog в приложении для Android

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

}

+0

Так ваше приложение падает после того, как появится ProgressDialog это? Что показывает ваш логарифм? – shyam

+0

Почему 'Thread'? –

+0

", но после этого приложение не работает" - что это значит? сбой приложений? – eldjon

ответ

0

вы можете использовать класс AsyncTask, чтобы сделать что-то вроде этого:

после метода 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); 
    } 
} 

определить эту переменную как глобальную переменную:

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

в 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(); 
} 
Смежные вопросы