0

我在将结果值返回到Android 的异步类中onPostExecute()的函数时遇到问题。onBackground()

我想做的是使用socket.io在数据库中搜索指定的联系人姓名,然后找到它;return true以便onPostExecute在找到联系人后我可以在那里做一些事情。如果没有找到,false应退回并做其他事情onPostExecute()。我将boolean全局值“success”分别设置为trueorfalse并尝试将此值传递给onPostExecute(),但由于某种原因,该值是onPostExecute()在调用之后分配的......必须与异步操作有关,但由于我不是专家,我希望有人能给我一些关于如何正确执行此操作的提示,以便在检查值boolean之前更新onPostExecute()值。

这是我的代码:

public class AsynchronicTask extends AsyncTask<Object, Void, Boolean> {

SocketIO socket = null;
AsyncObject asyncObject = null;
Boolean success = false;

@Override
protected Boolean doInBackground(final Object... argument) {
    this.asyncObject = (AsyncObject) argument[0];

    try {
        System.out.println("Trying to connect to: "
                + asyncObject.getURL());
        socket = new SocketIO(asyncObject.getURL());
        socket.connect(new IOCallback() {

            @Override
            public void onConnect() {
                JSONObject queriedUsername = new JSONObject();
                try {
                    queriedUsername.put("Username", asyncObject.getQueryInput());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                socket.emit("clientRequestSearchUsername", queriedUsername);
            }

            @Override
            public void onDisconnect() {
            }

            @Override
            public void onError(SocketIOException arg0) {
            }

            @Override
            public void onMessage(String arg0, IOAcknowledge arg1) {
            }

            @Override
            public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
            }

            @Override
            public void on(final String message, IOAcknowledge argIO,
                    final Object ... arg) {
                if (message.equals(asyncObject.getServerMessage())) {
                    if (arg[0].equals("null")) {
                        Log.e("ERROR", "No Result Found");
                        success = false;
                    } else {
                        success = true;
                        Log.d("DEBUG", "RESULT OK!");
                    }
                };
            }
        });

    } catch (MalformedURLException e) {
        Log.e("error", "Wrong Server URL");
        e.printStackTrace();
    }

return success;
}

@Override
protected void onPostExecute(Boolean result) {
    Log.d("DEBUG", result.toString());

    // Give reply when username query has finished
     if (result.equals(true)){
     Log.d("DEBUG", "Contact found, adding to contactlist");
     // Populate data in contactViewAdapter
     asyncObject.getContactListAdapter().populateAdapter(asyncObject.getQueryInput());
     Toast.makeText(asyncObject.getContext(), "Contact added", Toast.LENGTH_SHORT).show();
     } 
     else { 
         Log.d("DEBUG", "No Success adding contact, no contact found");
         Toast.makeText(asyncObject.getContext(), "Username not existent, no contact added", Toast.LENGTH_SHORT).show(); 
     }  
 }
 }
4

1 回答 1

1

发生这种情况是因为在调用方法之前doInBackground(...)返回值。SocketIO 在其后台线程中建立连接,这就是为什么它需要一些时间来执行此操作。您的解决方案:不要使用 AsyncTask。只需创建如下内容:onnew IOCallback()

void yourMethod (AsyncObject asyncObject, YourListener listener) {
    System.out.println("Trying to connect to: " + asyncObject.getURL());
    socket = new SocketIO(asyncObject.getURL());
    socket.connect(new IOCallback() {

        @Override
        public void onConnect() {
            JSONObject queriedUsername = new JSONObject();
            try {
                queriedUsername.put("Username", asyncObject.getQueryInput());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            socket.emit("clientRequestSearchUsername", queriedUsername);
        }

        @Override
        public void onDisconnect() {
        }

        @Override
        public void onError(SocketIOException arg0) {
        }

        @Override
        public void onMessage(String arg0, IOAcknowledge arg1) {
        }

        @Override
        public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
        }

        @Override
        public void on(final String message, IOAcknowledge argIO,
                final Object ... arg) {
            if (message.equals(asyncObject.getServerMessage())) {
                boolean success;
                if (arg[0].equals("null")) {
                    Log.e("ERROR", "No Result Found");
                    success = false;
                } else {
                    success = true;
                    Log.d("DEBUG", "RESULT OK!");
                }
                listener.ready(success);
            }
        }
    }
}

代码YourListener

public interface YourListener {

    public void ready(boolean value);
}

只需在您的课程中调用此方法:

yourMethod(asyncObject, new YourListener() {
    @Override
    public void ready(boolean value) {
            // copy here your code from onPostExecute
        }
    });
于 2015-06-29T00:21:02.947 回答