如何调用 AsyncTask 中的方法?在我的asynctask中,它是我的java文件“xyz”中的一个内部类,当用户单击按钮时,它应该调用“xyz”中的一个方法,该方法也恰好是一个alertDialog,我知道它调用它,但是当它到达该方法时,应用程序崩溃并给出运行时异常,该异常显示“无法在未调用 Looper.prepare() 的线程内创建处理程序”。我在这里查找了示例,但它引发了相同的运行时异常。我怎样才能让它发挥作用?是否可以从 asynctask 内部调用外部方法? 这是调用该方法的代码 fragment :
private class DownloadFilesTask extends AsyncTask<Void,Void,Void> {
private LoginActivity loginActivity;
public DownloadFilesTask(LoginActivity loginActivity){
this.loginActivity=loginActivity;
}
@Override
protected Void doInBackground(Void... voids) {
long start=System.currentTimeMillis();
in=null;
try {
website=new URI(URL);
request.setURI(website);
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpPost httpPost=new HttpPost(URL);
List<NameValuePair>nameValuePairs=new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name",name));
nameValuePairs.add(new BasicNameValuePair("pwd",pwd));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
response=httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
try {
in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
try {
String line=in.readLine();
long end=System.currentTimeMillis();
long times=end-start;
String time=String.valueOf(times);
System.out.println(name);
System.out.println(NAME_PATTERN);
System.out.println(pwd);
System.out.println(PWD_PATTERN);
if (name.equals(NAME_PATTERN) && (pwd.equals(PWD_PATTERN))) {
bloggedIn=true;
System.out.println("Youre right");
}else
{
bloggedIn=false;
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void onPostExecute(String line, String time) {
if(bloggedIn=true){
navigateToMainActivity(time);
}else{ if (bloggedIn=false){
newp(line,time);
}
}
}
}
这是调用的方法:
public void navigateToMainActivity(String timetoo) {
al=new AlertDialog.Builder(LoginActivity.this);
al.setTitle("Welcome");
al.setMessage("Hey there");
al.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(LoginActivity.this, Main.class));
}
});
al.show();
}
最佳答案
看起来您需要 doInBackground
在完成时返回 true
或 false
。您需要 doInBackground
来返回 boolean 值。试试这个:
@Override
protected Boolean doInBackground(Void... arg0)
{
// your stuff
return bloggedIn; // instead of null or return the boolean where you are setting it true or false
}
那么你的onPostExecute
应该如下所示:
@Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if(result){
navigateToMainActivity(time);
}else{
newp(line,time);
}
}
关于java - 单击按钮后如何使用异步任务调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33636708/