【问题标题】:AsyncTask has errors - beginnerAsyncTask 有错误 - 初学者
【发布时间】:2013-02-17 11:14:07
【问题描述】:

最终,我希望此方法在文本文档中查找一些值,并返回真存在的用户名和密码。但是我在实现 AsyncTask 时遇到了一些问题。我尝试按照http://developer.android.com/reference/android/os/AsyncTask.html 的指南进行操作,但没有成功。

我在 doInBackground 方法的返回类型上遇到的错误是“返回类型与 AsyncTask.doInBackground(String[]) 不兼容”

    private class AuthenticateUser extends AsyncTask<String, Integer, Boolean>
    {
        String user;
        String pass;

        protected void onPreExecute(String uname, String passwd)
        {
            user = uname;
            pass = passwd;
        }

        protected boolean doInBackground(String... strings)
        {
            return true;
        }

        protected boolean onPostExecute(boolean v)
        {
            return v;
        }
    } 

我知道这根本不是验证用户的好方法。我只是想弄清楚这一点。谢谢。

【问题讨论】:

  • 您是否要覆盖AsyncTaskdoInBackground 方法?
  • 只需将Override 放在doInBackground 之前,这将根据AsyncTask&lt;String, Integer, Boolean&gt; 中传递的参数自动为您提供doInBackground 方法的默认结构
  • 尝试使用布尔类而不是原始布尔值将protected boolean doInBackground(String... strings) 更改为protected Boolean doInBackground(String... strings)

标签: java android android-asynctask


【解决方案1】:

这里的问题是 AsyncTask 扩展是通用的,需要三种类型:AsyncTask&lt;Params, Progress, Result&gt; 可能是 Void 或类,但不是原始数据类型。

所以发生的事情是你告诉编译器 doInBackground 返回一个原始布尔值,但它期待一个布尔类的实例。因此您会收到“返回类型不兼容”错误。

只需将protected boolean doInBackground(String... strings) 更改为protected Boolean doInBackground(String... strings) 就可以了。

【讨论】:

  • 感谢 Oren,已对其进行了排序。但是,我还有另一个我忘记提及的错误。当我这样做时,我无法将 AuthenticateUser 解析为一种类型:new AuthenticateUser.execute("path/to/file.txt");
  • 即使 AuthentcateUser 是子类,我是否愿意这样做?
  • private class AuthenticateUser private 部分可能与此有关。 this usage example 可以帮助你。请注意,异步任务的类是私有的,因为它位于另一个公共类的范围内。您可以遵循该设计或只是将您的 AuthenticateUser 课程公开(取决于您的预期用途)。旁注:如果 Stack Overflow 上的答案对您有所帮助,您应该接受它,这样它也可以帮助其他人。
【解决方案2】:
 new AuthenticateUser().execute(username, password);

.

 private class AuthenticateUser extends AsyncTask<String, Void, Boolean>
    {
        String user;
        String pass;

        protected Boolean doInBackground(String... strings)
        {
            this.user = strings[0];
            this.pass = strings[1];

            //authen
            return true;
        }

        protected void onPostExecute(Boolean result)
        {
             //do stuff when successfully authenticated 
        }
    } 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2017-09-20
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多