我在将结果值返回到Android 的异步类中onPostExecute()
的函数时遇到问题。onBackground()
我想做的是使用socket.io在数据库中搜索指定的联系人姓名,然后找到它;return
true
以便onPostExecute
在找到联系人后我可以在那里做一些事情。如果没有找到,false
应退回并做其他事情onPostExecute()
。我将boolean
全局值“success”分别设置为true
orfalse
并尝试将此值传递给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();
}
}
}