你们可以查看我的代码,我不知道它是否构造正确,我需要在doInBackGround过程完成后显示toast并运行一个类。好吧,它不起作用,所以你们可以在这里帮助我。谢谢。
这是我的代码:
**
class phpconnect extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Main.this);
pDialog.setMessage("Logging in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("eadd", inputEmail.getText().toString()));
postParameters.add(new BasicNameValuePair("password", inputPassword.getText().toString()));
//Passing Parameter to the php web service for authentication
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2:8080/TheCalling/log_in.php", postParameters); //Enter Your remote PHP,ASP, Servlet file link
String res=response.toString();
//res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
} catch (Exception e) {
return "1";
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
if(result.equalsIgnoreCase("1")){
//Display Toast
Toast.makeText( getApplicationContext(),"Sorry!! Incorrect Username or Password",Toast.LENGTH_SHORT ).show();
}else{
Toast.makeText( getApplicationContext(),"Correct Username or Password",Toast.LENGTH_SHORT ).show();
Intent i = new Intent(Main.this,MainMenu.class);
startActivity(i);
}
}
**
答案 0 :(得分:1)
将Context传递给此AsyncTask的构造函数。 AsyncTask不会扩展Context本身,因此您不能使用getApplicationContext()
class phpconnect extends AsyncTask<String, String, String>{
private final Context mContext;
public phpconnect(final Context context) {
mContext = context;
}
[...]
protected void onPostExecute(String result) {
[...]
Toast.makeText( mContext,"...",Toast.LENGTH_SHORT ).show();
[...]
}
编辑:还要在if子句中添加NullPointer保护。类似的东西:
if(result != null && result.equalsIgnoreCase("1")){
答案 1 :(得分:0)
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
有关详细信息,请查看此link