我的要求: -
在我的Android项目中,我使用 javamail 连接到 gmail .. 所以,我想要当我点击按钮时,一个进度对话框将启动,并在后台它会尝试连接到gmail ..如果用户名和密码是正确的,意味着它连接到gmail ..然后将进入下一个活动 ..否则会关闭进度对话框并显示祝酒 - "出现问题"
所以我有这个: -
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
pdialog = ProgressDialog.show(context, "", "Please wait...", true);
session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
});
RetreiveFeedTask task = new RetreiveFeedTask();
task.execute();
}
});
}
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try{
Transport transport = session.getTransport("smtp");
// Enter your correct gmail UserID and Password
transport.connect("smtp.gmail.com", username, password);
} catch(Exception e) {
//e.printStackTrace();
Toast.makeText(context, "something is wrong", Toast.LENGTH_SHORT).show();
}
return null;
}
@Override
protected void onProgressUpdate(Void... result) {
pdialog.show();
}
@Override
protected void onPostExecute(String result) {
pdialog.dismiss();
iget = new Intent(context,NextScreen.class);
startActivity(iget);
}
}
但问题是: - 如果它连接到gmail id然后它进入下一个屏幕...如果我输入错误的用户名/密码然后它崩溃..在哪里是问题在我的代码??
答案 0 :(得分:2)
Toast
中的 doInBackground()
是问题。
您无法制作任何
UI operations in doInBackground()
将一些标记(如everythingOk=true/false
)返回onPostExecute()
&amp;根据标志显示Toast
。
class RetreiveFeedTask extends AsyncTask<String, Void, Boolean> {
boolean everythingOk=false;
@Override
protected Boolean doInBackground(String... params) {
try{
everythingOk=true;
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", username, password);
} catch(Exception e) {
everythingOk=false;
}
return everythingOk;
}
@Override
protected void onProgressUpdate(Void... result) {
pdialog.show();
}
@Override
protected void onPostExecute(Boolean result) {
pdialog.dismiss();
if(result==true){
iget = new Intent(context,NextScreen.class);
startActivity(iget);
}
else{
Toast.makeText(context, "something is worng", Toast.LENGTH_SHORT).show();
}
}
}
答案 1 :(得分:1)
试试这个:
runOnUiThread(new Runnable()
{
Toast.makeText(context, "something is worng",Toast.LENGTH_SHORT).show();
})
类似的问题: Can i have an example of displaying a toast using runOnUiThread.