0

下面的代码给出了 Fatal Exception Async Task #2 就行了v1.setEnabled(false)

这意味着在成功调用时禁用按钮。之前的v.setEnabled(false);后台任务工作正常。请帮忙 :(

public void onClick(View v) {
    Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
    //this one would work
    //v.setEnabled(false);

    final View v1=v;
    mRegisterTask1 = new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground(Void... params) {
        boolean success = 
            ServerUtilities.receipt (((String)v1.getTag()).substring(3),"acknowledged");

        if (success) {
            //this one causes Async Task exception
            v1.setEnabled(false);
        } 
        else {
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        mRegisterTask1 = null;
    }
4

3 回答 3

5

您不能从后台线程更改 UI 状态。在主线程中调用的
AsyncTaskonPreExecute()和方法。 看一看 :onPostExecute()

public void onClick(View v) {
    Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
    //this one would work
    //v.setEnabled(false);


    final View v1=v;
    mRegisterTask1 = new AsyncTask<Void, Void, Boolean>() {

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean success =
                    ServerUtilities.receipt (((String)v1.getTag()).substring(3),"acknowledged");


            return success;
        }

        @Override
        protected void onPostExecute(Bolean result) {

        if (result) {
                //this one causes Async Task exception
                v1.setEnabled(false);
            } else {

            }

            mRegisterTask1 = null;
        }
    }
}
于 2013-02-04T10:16:52.753 回答
0

您需要从 UI 线程更改小部件。方法onProgressUpdateOnPostExecute在 UI therad 中执行。因此,您可以考虑将代码移至后者。

于 2013-02-04T10:18:42.583 回答
0

将ui修改移至onPostExecute

boolean success = false;

protected Void doInBackground(Void... params) {
      success = ServerUtilities.receipt (((String)v1.getTag()).substring(3),"acknowledged");

        if (success) {
               //this one causes Async Task exception
                 v1.setEnabled(false);
          } else {

           }
                    return null;
             }
@Override
 protected void onPostExecute(Void result) {
      if (success) {
         //this one causes Async Task exception
            v1.setEnabled(false);
        } else {

        }
       mRegisterTask1 = null;
  }
于 2013-02-04T10:16:01.160 回答