ProgressDialog não aparece no AsyncTask
Estou criando um aplicativo para Android que depende dos dados que o aplicativo recebe do banco de dados. Para obter esses dados eu tenho a seguinte classe (esta classe obtém dados do banco de dados no json, traduz e retorna):
public class Json {
public String jsonResult;
private Activity activity;
private String url = "http://json.example.org/json.php";
private String db, query;
public Json(Activity activity) {
this.activity = activity;
}
public String accessWebService(String db, String query) {
JsonReadTask task = new JsonReadTask();
this.db = db;
this.query = query;
task.execute(new String[] { url });
try {
task.get();
} catch (InterruptedException e) {
Toast.makeText(activity.getApplicationContext(),
"FATAL ERROR: The thread got interrupted", Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
Toast.makeText(activity.getApplicationContext(),
"FATAL ERROR: The thread wasn't able to execute", Toast.LENGTH_LONG).show();
}
return jsonResult;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(activity);
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
// add post data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("db", db));
nameValuePairs.add(new BasicNameValuePair("query", query));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
if (jsonResult.isEmpty()) {
Toast.makeText(activity.getApplicationContext(),
"Error, connection is up but didn't receive data. That's strange...",
Toast.LENGTH_LONG).show();
this.cancel(true);
}
} catch (ClientProtocolException e) {
//Toast.makeText(activity.getApplicationContext(),
// "Error, Client Protocol Exception in JSON task",
// Toast.LENGTH_LONG).show();
Log.i("Json", "Error, Client Protocol Exception in JSON task");
this.cancel(true);
} catch (IOException e) {
//Toast.makeText(activity.getApplicationContext(),
// "Error, Please check your internet connection",
// Toast.LENGTH_LONG).show();
Log.i("Json", "Error, Please check your internet connection");
this.cancel(true);
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
Toast.makeText(activity.getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
return answer;
}
}
}// end async task
}
Percebi que meu aplicativo congela enquanto acessa o banco de dados. Depois de algum googling eu descobri que era o método .get () no método accessWebService () que causava isso. Eu tentei implementar um progressDialog assim (eu também deletei o método .get ()):
private final ProgressDialog dialog = new ProgressDialog(activity);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
protected void onPostExecute(String result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
mas a caixa de diálogo não apareceu e recebi NullPointerExceptions porque o aplicativo só funciona quando há dados:
result = json.accessWebService(db, query);
(talvez uma coisa importante mencionar: eu também uso este método em forloops)
Então, agora, minha pergunta é: Como posso alterar meu aplicativo para obter um ProgressDialog enquanto acedendo ao banco de dados e sem obter NullPointerExceptions? Eu temo que eu precise reestruturar todo o meu aplicativo e se eu tiver que fazer isso, como faço isso? Espero que vocês entendam minha pergunta e tenham uma correção para isso, porque eu realmente preciso de ajuda. Desde já, obrigado.
P.S. Desculpe se meu inglês não é tão bom, eu não sou um falante nativo.