【问题标题】:Problems with executing an AsyncTask within a static function在静态函数中执行 AsyncTask 的问题
【发布时间】:2012-07-24 14:44:00
【问题描述】:

我正在尝试从静态函数执行 doInBackground AsycTask,但是当我尝试输入 Void 的参数时,我收到一个 Java 错误,说“Void”不适用于该任务 '字符串,虚空,布尔'

无论如何,这是我的代码:

public class RequestHandler extends AsyncTask<URL, Void, Boolean> {

    //atributes for Async
    private static Context context;
    private RequestHandler origin;

 // Constructor
    public RequestHandler(Context c) {

        origin = this;
        context = c;

    }

   public static boolean doLogin(String username, String password) {
       String URL = "http://127.0.0.1:1337";
new RequestHandler(context).execute(URL, Void, false); // what do I put here?  
   }


    @Override
    protected Boolean doInBackground(URL... params) {
        // TODO Auto-generated method stub
        URL url = null;
        try {
           HttpURLConnection urlConnection = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
           try {
             InputStream in = null;
            try {
                in = new BufferedInputStream(urlConnection.getInputStream());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             readStream(in);
           } finally {

           }
        return false;

           }
            private String readStream(InputStream is) {
                try {
                  ByteArrayOutputStream bo = new ByteArrayOutputStream();
                  int i = is.read();
                  while(i != -1) {
                    bo.write(i);
                    i = is.read();
                  }
                  return bo.toString();
                } catch (IOException e) {
                  return "";
                }
            }
}

【问题讨论】:

    标签: android function static android-asynctask


    【解决方案1】:
    1. 将 'doLogin 方法放在 AsyncTask 类之外
    2. new RequestHandler(context).execute(URL);
    3. protected Boolean doInBackground(String... params) {....}

    【讨论】:

    • 什么!?将 DoLogin 放在课堂之外? !??
    • 是的,你为什么将我链接到异步教程?我知道所有变量都传递到哪里。
    • 我只是说,我不需要教程,我只需要一个基本的答案,因为我很困惑。
    【解决方案2】:

    您在 doLogin 方法中调用 RequestHandler 时,您正尝试使用 Void 作为对象,但它是一种类型,请尝试将该行更改为:

    new RequestHandler(context).execute(URL, null, false);
    

    并让您的 AsyncTask 改为返回 null。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2011-06-19
      相关资源
      最近更新 更多