我在 AsyncTask 中从数据库中获取数据,如果它为空,我想 Toast 一个警告文本。我在 AsyncTask 中尝试过,但我了解到它没有在工作线程中调用。这是我的 doInBackground 方法:
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet( "http://191.162.2.235/getProducts.php?login=1&user_name="+UserName+"&user_pass="+Password);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
if ( result == null ) {
// Toast.makeText(getApplicationContext(), "You entered wrong values.", Toast.LENGTH_LONG).show();
asyncTask.cancel(true);
Intent inte=new Intent(MainActivity.this, MainActivity.class);
inte.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
inte.addCategory(Intent.CATEGORY_HOME);
startActivity(inte);
}
}
catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
我取消了任务并在我的代码中创建了一个新意图。你不在乎他们。你看 Toast.makeText.. 行,我试过这样,当然它会出错。我怎样才能做到这一点?如果在 AsyncTask 中没有调用它,我应该如何调用?